繁体   English   中英

如何测试响应实体的Spring mvc控制器测试?

[英]How to test Spring mvc controller tests for response entity?

控制器如下:

    @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);
  }

我找不到使用Spring mvc控制器测试ResponseEntity的方法。 任何人都可以帮我这个吗?

在Spring集成测试框架中,它为测试控制器提供了类MockMvc。

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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