2015-05-27 15 views
14

To jest moja metoda w moim kontrolera, który jest odnotowany przez @ControllerJak sprawdzić JSON w organizmie reakcji z 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; 
    } 

Oczekuję {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} jak mój JSON.

A to moja testy 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(); 
     } 
    } 

Oto wyjście konsoli:

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

Nawet result.getResponse().getContentAsString() jest pustym ciągiem.

Czy ktoś może zasugerować, w jaki sposób uzyskać mój JSON w mojej metodzie testu JUnit, aby móc ukończyć test.

Odpowiedz

9

Kod stanu 406 Not Acceptable oznacza, że ​​Spring nie mógł przekształcić obiektu w json. Możesz albo sprawić, by twoja metoda kontrolera zwracała ciąg i czyś return json.toString(); lub skonfigurować własną HandlerMethodReturnValueHandler. Sprawdź to podobne pytanie Returning JsonObject using @ResponseBody in SpringMVC

9

Używam TestNG do testowania mojej jednostki. Ale w Spring Test Framework oba wyglądają podobnie. Uważam więc nasz test będzie jak poniżej

@Test 
public void testAlertFilterView() throws Exception { 
    this.mockMvc.perform(get("/getServerAlertFilters/v2v2v2/"). 
      .andExpect(status().isOk()) 
      .andExpect(content().json("{'data':[{'useRegEx':'false','hosts':'v2v2v2'}]}")); 
    } 

Jeśli chcesz sprawdzić sprawdzić klucz json i wartości można użyć jsonpath .andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));

Może się okazać, że content().json() nie solveble proszę dodać

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

Powiązane problemy