在 Spring 中测试返回 ResponseEntity<> 的 POST 方法

GoR*_*ame 5 java junit spring spring-test mockito

我正在尝试测试在服务类中返回 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<>。我做错了什么以及如何解决这个问题?

Kai*_*ang 0

问题是您创建了Customer测试代码,这与生产代码Customer不同。Customer

所以 Mockito 无法匹配两者Customer,导致when/thenReturn表达式失败。因此service.addCustomer返回 anull并且您在测试结果中得到 AssertionError 。

可以使用any()matcher来解决这个问题:

when(service.addCustomer(any())).thenReturn(.....);
Run Code Online (Sandbox Code Playgroud)