正在嘗試用junit5和mockito測試我的web層(springboot,springmvc)。http方法的所有其他測試(get、put等)工作正常,但更新。遵循代碼。
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);
}
最后,測試:
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"
CustomerService中的update(...)方法只返回null。我不明白怎么回事。請給出建議。
問題在于這一行:
你應該把它改成
因為您的put請求主體是
JSON
,而不是真正的Customer
,所以when...thenReturn
語句沒有像您預期的那樣工作良好。被模擬的customerService
默認返回空值。這就是為什么你得到了一個空洞的回答。因此,你必須糾正參數匹配器,使其正確。