问题
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