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

时间:2019-02-25 13:56:19

标签: java spring spring-mvc 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

我在MyResponse中看到ModelAndView对象是第二个属性,但是response为空

如何检查此响应中返回的JSON字符串?

1 个答案:

答案 0 :(得分:0)

这里有一种方法,我希望我理解正确的问题,

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”)))

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

尝试一下

 MockMvcRequestBuilders
.post("/servlet/api/update")
.content("{\"id\":1,\"toggle\":true}]")
.session(httpSession)
.contentType(MediaType.APPLICATION_JSON)
.andExpect(content().string(containsString("value")));