2015-05-27 47 views
14

這是我我的控制器內的方法,它是通過@Controller如何檢查JSON響應體mockMvc

@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 = [] 

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

有人可以請建議如何讓我的JUnit在我的JUnit測試方法,以便我可以完成我的測試用例。

回答

9

我使用TestNG進行單元測試。但在Spring測試框架中,它們看起來都很相似。所以我相信你的測試像下面

@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()不solveble請加

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;