Trying to test my web tier (spring boot, spring mvc) with junit5 and mockito. All other tests on http methods (get, put, ...) are working fine but the update. Following the code.
Controller:
@PutMapping(value = "{id}")
public ResponseEntity<?> putOne(@PathVariable Integer id, @Valid @RequestBody Customer customerToUpdate) {
Customer updated = customerService.update(id, customerToUpdate);
return ResponseEntity.ok(updated);
}
Service:
public Customer update(Integer customerId, Customer customerToUpdate) {
Customer customerFound = customerRepository.findById(customerId).orElseThrow(() -> {
throw new CustomerControllerAdvice.MyNotFoundException(customerId.toString());
});
customerToUpdate.setId(customerFound.getId());
return customerRepository.save(customerToUpdate);
}
Finally the test:
static final Customer oneCustomer = Customer.of(3,"john", LocalDate.of(1982, 11, 8));
@Test
void putOneTest() throws Exception {
when(customerService.update(oneCustomer.getId(), oneCustomer)).thenReturn(oneCustomer);
mockMvc.perform(put(CUSTOMER_URL oneCustomer.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(oneCustomer)))
.andDo(print())
.andExpect(jsonPath("$.name").value(oneCustomer.getName()))
.andExpect(jsonPath("$.birthDate").value(oneCustomer.getBirthDate().toString()))
.andExpect(status().isOk());
}
Result:
java.lang.AssertionError: No value at JSON path "$.name"
update(...) method in CustomerService return just null. Can't understand way. Please advice.
CodePudding user response:
The problem is this line:
when(customerService.update(oneCustomer.getId(), oneCustomer)).thenReturn(oneCustomer);
You should change it to
when(customerService.update(eq(oneCustomer.getId()), any())).thenReturn(oneCustomer);
Because your put request body is a JSON
, not a real Customer
, the when...thenReturn
statement didn't work well as you expected. The mocked customerService
returns a null by default. This is why you got a empty response. So you must to correct the argument matcher to make it.