mockmvcjsonpath响应的主体为空?

yhived7q  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(415)

测试控制器会出现以下错误:java.lang.assertionerror:json路径“$.firstname”处没有值。很显然,我的回答是空的,因为某些原因。控制器是restcontroller,我正确地模拟了服务。有人能帮我吗?
测试类:

@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"));

    }

请求是正确的,但显然响应的主体是空的(请参阅下面的控制台输出):

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 = []

控制器代码:

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

xytpbqjk1#

问题在于:

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

在内部,mockito使用对象类的equals()方法将作为参数传递给该方法的对象与配置的对象进行比较。如果不重写equals(),则使用java.lang.object的equals(),它只比较引用,即如果两个变量都指向堆中的同一个对象。在当前示例中,employe类(可能)没有实现equals()方法。当创建一个新对象时,引用不是一个相同的引用,因此mockito将无法通过验证。
因为employee对象是从json序列化的,所以它不是同一个对象。
你可以用 Mockito.any() 或者 Mockito.any(Employee.class) .

相关问题