如何在 Spring MVC 测试中检查 JSON 响应

2024-01-09

我在 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,只返回一个 POJO 对象(MyResponse) 序列化为 JSON 响应

我正在看MyResponse对象作为第二个属性ModelAndView, but response is 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",is("value")))

您可以将其用于每个键和值。

Or

尝试这个 ,

 MockMvcRequestBuilders
.post("/servlet/api/update")
.content("{\"id\":1,\"toggle\":true}]")
.session(httpSession)
.contentType(MediaType.APPLICATION_JSON)
.andExpect(content().string(containsString("value")));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Spring MVC 测试中检查 JSON 响应 的相关文章

随机推荐