我正在尝试测试在服务类中返回 ResponseEntity<> 的 POST 方法:
public ResponseEntity<Customer> addCustomer(Customer customer) {
[validation etc...]
return new ResponseEntity<>(repository.save(customer), HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
我在做什么:
@Test
public void addCustomer() throws Exception {
String json = "{" +
"\"name\": \"Test Name\"," +
"\"email\": \"test@email.com\"" +
"}";
Customer customer = new Customer("Test Name", "test@email.com");
when(service.addCustomer(customer))
.thenReturn(new ResponseEntity<>(customer, HttpStatus.OK));
this.mockMvc.perform(post(CustomerController.URI)
.contentType(MediaType.APPLICATION_JSON)
.content(json)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").exists())
.andExpect(jsonPath("$.name", is("Test Name")))
.andExpect(jsonPath("$.email", is("test@email.com")))
.andExpect(jsonPath("$.*", hasSize(3)))
.andDo(print());
}
Run Code Online (Sandbox Code Playgroud)
当我运行测试时我收到:
java.lang.AssertionError: No value at JSON path "$.id"
Run Code Online (Sandbox Code Playgroud)
Status = 200。据我了解,Mockito 没有返回该对象。其他方法(如 GET)工作得很好,但它们返回对象,而不是 ResponseEntity<>。我做错了什么以及如何解决这个问题?