'Test POST method that return ResponseEntity<> in Spring
I'm trying to test my POST method that returns ResponseEntity<> in service class:
public ResponseEntity<Customer> addCustomer(Customer customer) {
[validation etc...]
return new ResponseEntity<>(repository.save(customer), HttpStatus.OK);
}
What I'm doing:
@Test
public void addCustomer() throws Exception {
String json = "{" +
"\"name\": \"Test Name\"," +
"\"email\": \"[email protected]\"" +
"}";
Customer customer = new Customer("Test Name", "[email protected]");
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("[email protected]")))
.andExpect(jsonPath("$.*", hasSize(3)))
.andDo(print());
}
When I run the test I've receiving:
java.lang.AssertionError: No value at JSON path "$.id"
and Status = 200. So as far as I understand Mockito is not returning the object. The other methods like GET work perfectly fine, but they return the object, not the ResponseEntity<>. What I'm doing wrong and how can I fix that?
Solution 1:[1]
The problem is that you have created a Customer in test code, this Customer is different from the Customer in production code.
So Mockito cannot match the two Customer, and cause when/thenReturn expression to fail. Thus service.addCustomer return a null and you get AssertionError in test result.
You can use any() matcher to solve this problem:
when(service.addCustomer(any())).thenReturn(.....);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kai-Sheng Yang |
