Skip to content

Commit 049c03c

Browse files
adding controller method for patch
1 parent e01ff1d commit 049c03c

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

src/main/java/guru/springfamework/controllers/v1/CustomerController.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,10 @@ public ResponseEntity<CustomerDTO> updateCustomer(@PathVariable Long id, @Reques
4646
return new ResponseEntity<CustomerDTO>(customerService.saveCustomerByDTO(id, customerDTO),
4747
HttpStatus.OK);
4848
}
49+
50+
@PatchMapping({"/{id}"})
51+
public ResponseEntity<CustomerDTO> patchCustomer(@PathVariable Long id, @RequestBody CustomerDTO customerDTO){
52+
return new ResponseEntity<CustomerDTO>(customerService.patchCustomer(id, customerDTO),
53+
HttpStatus.OK);
54+
}
4955
}

src/main/java/guru/springfamework/services/CustomerServiceImpl.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,12 @@ public CustomerDTO patchCustomer(Long id, CustomerDTO customerDTO) {
8585
customer.setLastname(customerDTO.getLastname());
8686
}
8787

88-
return customerMapper.customerToCustomerDTO(customerRepository.save(customer));
88+
CustomerDTO returnDto = customerMapper.customerToCustomerDTO(customerRepository.save(customer));
89+
90+
returnDto.setCustomerUrl("/api/v1/customer/" + id);
91+
92+
return returnDto;
93+
8994
}).orElseThrow(RuntimeException::new); //todo implement better exception handling;
9095
}
9196
}

src/test/java/guru/springfamework/controllers/v1/CustomerControllerTest.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,4 +125,27 @@ public void testUpdateCustomer() throws Exception {
125125
.andExpect(jsonPath("$.lastname", equalTo("Flintstone")))
126126
.andExpect(jsonPath("$.customer_url", equalTo("/api/v1/customers/1")));
127127
}
128+
129+
@Test
130+
public void testPatchCustomer() throws Exception {
131+
132+
//given
133+
CustomerDTO customer = new CustomerDTO();
134+
customer.setFirstname("Fred");
135+
136+
CustomerDTO returnDTO = new CustomerDTO();
137+
returnDTO.setFirstname(customer.getFirstname());
138+
returnDTO.setLastname("Flintstone");
139+
returnDTO.setCustomerUrl("/api/v1/customers/1");
140+
141+
when(customerService.patchCustomer(anyLong(), any(CustomerDTO.class))).thenReturn(returnDTO);
142+
143+
mockMvc.perform(patch("/api/v1/customers/1")
144+
.contentType(MediaType.APPLICATION_JSON)
145+
.content(asJsonString(customer)))
146+
.andExpect(status().isOk())
147+
.andExpect(jsonPath("$.firstname", equalTo("Fred")))
148+
.andExpect(jsonPath("$.lastname", equalTo("Flintstone")))
149+
.andExpect(jsonPath("$.customer_url", equalTo("/api/v1/customers/1")));
150+
}
128151
}

0 commit comments

Comments
 (0)