尝试用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"
update(…)方法在CustomerService返回null。不能理解的方式。请建议。
问题出在这一行:
when(customerService.update(oneCustomer.getId(), oneCustomer)).thenReturn(oneCustomer);
应该改成
when(customerService.update(eq(oneCustomer.getId()), any())).thenReturn(oneCustomer);
因为您的put请求体是JSON
,而不是真正的Customer
,所以when...thenReturn
语句没有像您预期的那样工作得很好。默认情况下,模拟的customerService
返回null。这就是为什么你的回复是空的。所以你必须纠正参数匹配器,使它。