返回ResponseEntity<>的测试POST方法在春天

时间:2018-03-26 11:48:04

标签: java spring junit mockito spring-test

我正在尝试测试返回ResponseEntity<>的POST方法在服务类:

public ResponseEntity<Customer> addCustomer(Customer customer) {
    [validation etc...]
    return new ResponseEntity<>(repository.save(customer), HttpStatus.OK);
}

我在做什么:

    @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());
}

当我进行测试时,我收到了:

java.lang.AssertionError: No value at JSON path "$.id"

和Status = 200.据我所知,Mockito没有返回对象。像GET这样的其他方法工作得很好,但它们返回对象,而不是ResponseEntity&lt;&gt;。我做错了什么,我该如何解决?

0 个答案:

没有答案