![](/img/trans.png)
[英]Test Spring MVC response pattern (Ignore a json field in the items in the response )
[英]How to check JSON response in Spring MVC test
我在web.xml中定义了一个servlet,所以我在Controller中定义了它,仅用于MyResource
测试:
@Controller
public class TestMyServlet {
MyResource servlet;
@Autowired
AutowireCapableBeanFactory beanFac;
@PostConstruct
void init() {
servlet = new MyResource();
beanFac.autowireBean(servlet);
}
@RequestMapping(value = "/servlet/api/update", method = RequestMethod.POST)
public MyResponse handle(HttpServletRequest request, HttpServletResponse response, @RequestBody String json) {
return servlet.update(json);
}
然后,我使用MockHttpServletRequestBuilder
对其进行测试:
MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders
.post("/servlet/api/update")
.content("{\"id\":1,\"toggle\":true}]")
.session(httpSession)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = this.mockMvc.perform(mockHttpServletRequestBuilder)
.andDo(MockMvcResultHandlers.print())
.andReturn();
ModelAndView modelAndView = mvcResult.getModelAndView().getModelMap();
String response = mvcResult.getResponse().getContentAsString();
在servlet中,我不使用ModelAndView
,只是返回一个序列化为JSON响应的POJO对象( MyResponse
)
我在ModelAndView
看到MyResponse
对象作为第二个属性,但是response
为null
如何检查此响应中返回的JSON字符串?
这里有一种方法,我希望我理解正确的问题,
MockMvcRequestBuilders
.post("/servlet/api/update")
.content("{\"id\":1,\"toggle\":true}]")
.session(httpSession)
.contentType(MediaType.APPLICATION_JSON)
.andExpect(jsonPath("$[0].key",is("value")));
andExpect(jsonPath( “$ [0] .KEY”,是( “值”)))
您可以将其用于每个键和值。
要么
尝试这个 ,
MockMvcRequestBuilders
.post("/servlet/api/update")
.content("{\"id\":1,\"toggle\":true}]")
.session(httpSession)
.contentType(MediaType.APPLICATION_JSON)
.andExpect(content().string(containsString("value")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.