如何使用mockMvc检查响应体中的JSON

13 浏览
0 Comments

如何使用mockMvc检查响应体中的JSON

这是我在我的控制器中的方法,该方法由@Controller注解标注:

@RequestMapping(value = "/getServerAlertFilters/{serverName}/", produces = "application/json; charset=utf-8")
    @ResponseBody
    public JSONObject getServerAlertFilters(@PathVariable String serverName) {
        JSONObject json = new JSONObject();
        List filteredAlerts = alertFilterService.getAlertFilters(serverName, "");
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(filteredAlerts);
        json.put(SelfServiceConstants.DATA, jsonArray);
        return json;
    }

我期望的JSON是{"data":[{"useRegEx":"false","hosts":"v2v2v2"}]}

这是我的JUnit测试:

@Test
    public final void testAlertFilterView() {       
        try {           
            MvcResult result = this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").session(session)
                    .accept("application/json"))
                    .andDo(print()).andReturn();
            String content = result.getResponse().getContentAsString();
            LOG.info(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

这是控制台输出:

MockHttpServletResponse:
              Status = 406
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

即使result.getResponse().getContentAsString()是一个空字符串。

请问有人能够建议如何在我的JUnit测试方法中获取我的JSON,以便我可以完成我的测试用例吗?

0