如何使用 mockMvc 在响应正文中检查 JSON
2022-08-31 14:48:16
这是我在控制器中的方法,由@Controller
@RequestMapping(value = "/getServerAlertFilters/{serverName}/", produces = "application/json; charset=utf-8")
@ResponseBody
public JSONObject getServerAlertFilters(@PathVariable String serverName) {
JSONObject json = new JSONObject();
List<FilterVO> 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 = []
even 是一个空字符串。result.getResponse().getContentAsString()
有人可以建议如何在我的JUnit测试方法中获取我的JSON,以便我可以完成我的测试用例。