我有一个rest Controller 方法,该方法返回一个对象CompositeObject
,其中包含几个其他对象和结构(映射和列表)。我想编写一个测试,测试其余的get调用是否将对象与字段一起返回(即使这些字段的值为null),但我不知道如何映射下面的模拟mvc调用的响应:
String response = this.mockMvc.perform(get("/getclassdata?classCode=cs").accept("application/json"))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
该测试工作正常,但是我想检查返回的JSON是否是我感兴趣的对象(
CompositeObject
),并确保它包含所有必填字段。我该如何测试?测试框架中是否有类似于instanceof
的内容?谢谢你。
最佳答案
您可以使用com.fasterxml.jackson.databind.ObjectMapper
读取Json对POJO的响应:
ObjectMapper mapper = new ObjectMapper();
MvcResult mvcResult = mockMvc.perform(get("/example-endpoint")).andReturn();
ExampleResponse parsedResponse = mapper.readValue(mvcResult.getResponse().getContentAsByteArray(), ExampleResponse.class);
关于testing - 如何将模拟MVC GET调用映射到Java POJO?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42072681/