問題描述
這是我在控制器中的方法,由 @Controller
This is my method inside my controller which is annotated by @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;
}
我期待 {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]}
作為我的 json.
I am expecting {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]}
as my json.
這是我的 JUnit 測試:
And this is my JUnit test:
@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()
也是一個空字符串.
Even result.getResponse().getContentAsString()
is an empty string.
有人可以建議如何在我的 JUnit 測試方法中獲取我的 JSON,以便我可以完成我的測試用例.
Can someone please suggest how to get my JSON in my JUnit test method so that I can complete my test case.
推薦答案
我使用 TestNG 進行單元測試.但是在 Spring Test Framework 中,它們看起來都很相似.所以我相信你的測試如下所示
I use TestNG for my unit testing. But in Spring Test Framework they both looks similar. So I believe your test be like below
@Test
public void testAlertFilterView() throws Exception {
this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/").
.andExpect(status().isOk())
.andExpect(content().json("{'data':[{'useRegEx':'false','hosts':'v2v2v2'}]}"));
}
如果你想檢查檢查 json 鍵和值,你可以使用 jsonpath.andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));
If you want check check json Key and value you can use jsonpath
.andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));
您可能會發現content().json()
無法解決請添加
You might find thatcontent().json()
are not solveble please add
導入靜態 org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
這篇關于如何使用 mockMvc 檢查響應正文中的 JSON的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!