try 用junit5和mockito测试我的web层(spring boot、spring mvc).http方法的所有其他测试(get、put等)工作正常,但更新.
控制器:
@PutMapping(value = "{id}")
public ResponseEntity<?> putOne(@PathVariable Integer id, @Valid @RequestBody Customer customerToUpdate) {
Customer updated = customerService.update(id, customerToUpdate);
return ResponseEntity.ok(updated);
}
服务:
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);
}
最后,测试:
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());
}
结果:
java.lang.AssertionError: No value at JSON path "$.name"
更新(…)CustomerService中的方法仅返回null.我不明白怎么回事.请给出建议.