ITW*_*ker 5 testing jackson spring-boot mockmvc
我有一个rest控制器方法,它返回一个对象CompositeObject,其中包含几个其他对象和结构(地图和列表).我想编写一个测试,测试其余的get调用是否返回该对象以及字段(即使这些字段的值为null),但我不知道如何映射下面的模拟mvc调用的响应:
String response = this.mockMvc.perform(get("/getclassdata?classCode=cs").accept("application/json"))
                .andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();
Run Code Online (Sandbox Code Playgroud)
此测试工作正常,但我想检查返回的JSON是否是我感兴趣的对象(CompositeObject),并确保它包含所有必需的字段.我该如何测试呢?测试框架中有类似的东西instanceof吗?
谢谢.
您可以使用com.fasterxml.jackson.databind.ObjectMapper以下命令读取对 POJO 的 Json 响应:
ObjectMapper mapper = new ObjectMapper();
MvcResult mvcResult = mockMvc.perform(get("/example-endpoint")).andReturn();
ExampleResponse parsedResponse = mapper.readValue(mvcResult.getResponse().getContentAsByteArray(), ExampleResponse.class);
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           2000 次  |  
        
|   最近记录:  |