How to check JSON response in Spring MVC test

一个人想着一个人 提交于 2019-12-24 19:40:07

问题


I have a servlet defined in web.xml, so I defined it inside a Controller for testing only for 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);
     }

Then I test it using 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();

In servlet I don't use ModelAndView, just returning a POJO object (MyResponse) that is serialize to JSON response

I'm seeing MyResponse object as a second attribute in ModelAndView, but response is null

How can I check JSON string returned in this response?


回答1:


There is one way here, i hope i understood the question correct ,

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

you can use this for each key and value.

Or

try this ,

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


来源:https://stackoverflow.com/questions/54867824/how-to-check-json-response-in-spring-mvc-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!