2015-05-27 25 views
14

Đây là phương pháp của tôi bên trong bộ điều khiển của tôi mà được chú thích bởi @ControllerLàm thế nào để kiểm tra JSON trong cơ thể phản ứng với 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; 
    } 

Tôi hy vọng {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} như json tôi.

Và đây là thử nghiệm JUnit tôi:

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

Đây là giao diện điều khiển đầu ra:

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

Thậm chí result.getResponse().getContentAsString() là một chuỗi rỗng.

Ai đó có thể đề nghị cách lấy JSON của tôi trong phương pháp kiểm tra JUnit của tôi để tôi có thể hoàn thành trường hợp thử nghiệm của mình.

Trả lời

9

Mã trạng thái 406 Not Acceptable có nghĩa là Spring không thể chuyển đổi đối tượng thành json. Bạn có thể làm cho phương thức điều khiển của bạn trả về một String và làm return json.toString(); hoặc cấu hình của riêng bạn HandlerMethodReturnValueHandler. Kiểm tra câu hỏi tương tự này Returning JsonObject using @ResponseBody in SpringMVC

9

Tôi sử dụng TestNG để thử nghiệm đơn vị của mình. Nhưng trong Spring Test Framework, cả hai đều trông giống nhau. Vì vậy, tôi tin rằng thử nghiệm của bạn được như dưới đây

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

Nếu bạn muốn kiểm tra rà soát json Key và giá trị mà bạn có thể sử dụng jsonpath .andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));

Bạn có thể thấy rằng content().json() không solveble xin vui lòng thêm

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

Các vấn đề liên quan