简体   繁体   English

MockMVC JsonPath 响应有空体?

[英]MockMVC JsonPath response has empty body?

Testing the controller gives following error: java.lang.AssertionError: No value at JSON path "$.firstName".测试 controller 给出以下错误:java.lang.AssertionError:JSON 路径“$.firstName”处没有值。 Apparently the body of my response is empty for some reason.显然,由于某种原因,我的回复内容是空的。 Controller is a RestController and and i'm correctly mocking the service. Controller 是一个 RestController 并且我是正确的 mocking 服务。 Can someone help me?有人能帮我吗?

Testclass:测试类:

@WebMvcTest(EmployeeController.class)
class EmployeeControllerTest {
    Employee employee = new Employee();

    @Autowired
    private MockMvc mvc;

    @MockBean
    private EmployeeServiceImpl service;


    @BeforeEach
    public void initEmployee() {
        employee.setFirstName("John");
        employee.setLastName("Doe");
        employee.setPlace("xxxx");
        employee.setEmployeeTitle(EmployeeTitle.SENIOR_JAVA_DEVELOPER);
        employee.setEmployeeId(1L);

    }

    @Test
    public void createEmployeeAPI() throws Exception {

        when(service.addNewEmployee(employee)).thenReturn(employee);

        mvc.perform(MockMvcRequestBuilders
                .post("/employees")
                .content(asJsonString(employee))
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.firstName").value("John"));

    }

Request is correct but apparently the body is of the response is empty (see console output below):请求是正确的,但显然响应的主体是空的(参见下面的控制台 output):

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /employees
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"124"]
             Body = {"employeeId":1,"firstName":"John","lastName":"Doe","employeeTitle":"SENIOR_JAVA_DEVELOPER","place":"xxxx","photoURrl":null}
    Session Attrs = {}

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Controller code: Controller 代码:

@RestController
@RequestMapping("/employees")
public class EmployeeController extends ExceptionHandling {
    private final EmployeeService employeeService;

    @Autowired
    public EmployeeController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @PostMapping()
    public Employee addEmployee(@RequestBody Employee employee) {
        return employeeService.addNewEmployee(employee);
    }

The problem lies here:问题出在这里:

when(service.addNewEmployee(employee)).thenReturn(employee);

Internally Mockito uses an Object class's equals() method to compare object that has been passed to the method as an argument with object configured. Internally Mockito uses an Object class's equals() method to compare object that has been passed to the method as an argument with object configured. If equals() is not overridden then java.lang.Object's equals() is used which compares only the references, ie if both variables point to one and the same object in heap.如果 equals() 未被覆盖,则使用 java.lang.Object 的 equals() 仅比较引用,即如果两个变量都指向一个且相同的 object 在堆中。 In the current example, Employe class (probably) has no equals() method implemented.在当前示例中,Employe class(可能)没有实现 equals() 方法。 When providing expected a new object is created, references are not one and the same, so Mockito will fail the verification.当提供预期的一个新的 object 时,会创建一个新的 object,引用不一样,因此 Mockito 将无法通过验证。

Because the employee object is serialized from json, it is not the same object.因为员工object是从json序列化而来,所以不是同一个object。

You can fix this by using Mockito.any() or Mockito.any(Employee.class) .您可以使用Mockito.any()Mockito.any(Employee.class)来解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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