2015-05-27 16 views
14

ile tepki vücutta JSON kontrol etme Bu benim json olarak {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} bekliyorum @ControllermockMvc

@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; 
    } 

tarafından açıklamalı benim denetleyicisi içinde benim yöntemidir.

Ve bu benim JUnit testi:

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

bile result.getResponse().getContentAsString() boş bir dize: Burada

@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(); 
     } 
    } 

konsol çıkıştır.

JSON'umu JUnit test yöntemimde nasıl alacağımı önermek için lütfen birileri test durumumu tamamlayabilir.

cevap

9

406 Not Acceptable durum kodu, Spring'in nesneyi json'a dönüştüremediği anlamına gelir. Denetleyici yönteminizi bir String döndürüp return json.toString(); yapabilir veya kendi HandlerMethodReturnValueHandler'u yapılandırabilirsiniz. Benzer soruyu kontrol edin Returning JsonObject using @ResponseBody in SpringMVC

9

TestNG'yi birim testlerimde kullanıyorum. Ancak Bahar Testi Çerçevesinde ikisi de benzer görünüyor. Bu yüzden Ekleyiniz Sen content().json() solveble olmadığını bulabilirsiniz jsonpath .andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));

kullanabilirsiniz json Anahtarı ve değerini kontrol kontrol istiyorsanız gibi

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

aşağıya sınav olacağını düşünüyoruz

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

İlgili konular