2015-05-27 15 views
14

Questo è il mio metodo dentro il mio regolatore che viene annotata da @ControllerCome controllare JSON nel corpo di risposta con 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; 
    } 

Mi aspetto {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} come il mio JSON.

E questo è il mio test 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(); 
     } 
    } 

Ecco l'output della console:

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

Anche result.getResponse().getContentAsString() è una stringa vuota.

Qualcuno può suggerire come ottenere il mio JSON nel mio metodo di test JUnit in modo da poter completare il mio test case.

risposta

9

Il codice di stato 406 Not Acceptable indica che Spring non ha potuto convertire l'oggetto in json. È possibile rendere il metodo del controller restituire una stringa e fare return json.toString(); o configurare il proprio HandlerMethodReturnValueHandler. Controllare questa domanda simile Returning JsonObject using @ResponseBody in SpringMVC

9

Uso TestNG per il test dell'unità. Ma in Spring Test Framework entrambi sembrano simili. Quindi credo che il test sia come sotto

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

Se si desidera check check chiave JSON e il valore è possibile utilizzare jsonpath .andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));

Potreste scoprire che content().json() non sono solveble si prega di aggiungere

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

Problemi correlati