嘗試使用 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 中的 update(...) 方法只回傳 null。看不懂方法。請指教。
uj5u.com熱心網友回復:
問題是這一行:
when(customerService.update(oneCustomer.getId(), oneCustomer)).thenReturn(oneCustomer);
你應該把它改成
when(customerService.update(eq(oneCustomer.getId()), any())).thenReturn(oneCustomer);
因為您的 put 請求正文是 a JSON,而不是 real Customer,所以該when...thenReturn陳述句沒有像您預期的那樣運行良好。默認情況下,模擬customerService回傳 null。這就是為什么你得到一個空的回應。所以你必須糾正引數匹配器才能做到。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476773.html
上一篇:如何在另一個應用程式中打開由一個XamarinAndroid應用程式創建的SQLiteDB?
下一篇:不支持內容型別multipart/mixed/415UNSUPPORTED_MEDIA_TYPE(Spring SpringBoot升級后)
