これは私のコントローラ内のメソッドで、@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として期待しています。
これが私の 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 = []
Evenresult.getResponse().getContentAsString()
は空の文字列です。
テストケースを完了できるように、JUnit テスト メソッドで JSON を取得する方法を提案していただけませんか。
ベストアンサー1
私はユニットテストにTestNGを使用しています。しかし、Spring Test Frameworkではどちらも似ています。したがって、テストは以下のようになると思います。
@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")));
content().json()
解決できないと思われる場合は追加してください
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;