简体   繁体   中英

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\": \"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());
}

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?

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(.....);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM