简体   繁体   中英

How to test Spring mvc controller tests for response entity?

The controller is like:

    @RequestMapping(method = RequestMethod.GET, value = "/autocomplete")
    public ResponseEntity<String> autoComplete(@RequestParam("query") final String searchKey)
 {     
        List<String> list = ...     
        Gson gson = new Gson();
        String jsonString = gson.toJson(list);
        return new ResponseEntity<String>(jsonString, HttpStatus.OK);
  }

I couldn't find a way to test the ResponseEntity using Spring mvc controller. Could anyone help me with this?

In spring integration test framework, it provides class MockMvc to test controllers.

MockMvc mvc = MockMvcBuilders.webAppContextSetup(wac).build(); // was is a web application context.
MvcResult result = mvc
            .perform(
                    get("/autocomplete")
            .accept(
                    MediaType.APPLICATION_JSON))
            .andExpect(status().isOk()).andReturn();
String content = result.getResponse().getContentAsString();  // verify the response string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM