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

mon*_*123 8 java spring-mvc gson

控制器是这样的:

    @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);
  }
Run Code Online (Sandbox Code Playgroud)

我找不到使用 Spring mvc 控制器测试 ResponseEntity 的方法。有人可以帮我解决这个问题吗?

小智 8

在 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.
Run Code Online (Sandbox Code Playgroud)