如何使用mockMvc检查响应体中的JSON

Zee*_*han 34 java junit spring mocking spring-test-mvc

这是我的控制器里面的方法,注释方法是 @Controller

@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;
    }
Run Code Online (Sandbox Code Playgroud)

我期待着{"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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是控制台输出:

MockHttpServletResponse:
              Status = 406
       Error message = null
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []
Run Code Online (Sandbox Code Playgroud)

甚至result.getResponse().getContentAsString()是一个空字符串.

有人可以建议如何在我的JUnit测试方法中获取我的JSON,以便我可以完成我的测试用例.

Men*_*han 27

我使用TestNG进行单元测试.但在Spring Test Framework中,它们看起来都很相似.所以我相信你的测试如下

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

如果要检查json Key和值,可以使用jsonpath .andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));

您可能会发现content().json()无法解决,请添加

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

  • 当尝试解决方案时,我收到 `NoClassDefFoundError: org/skyscreamer/jsonassert/JSONAssert` (在 spring 的 `JsonExpectationsHelper` 中使用) (2认同)

med*_*088 10

406 Not Acceptable状态代码意味着春天不能将对象转换为JSON.您可以使控制器方法返回String并执行return json.toString();或配置自己的控制器方法HandlerMethodReturnValueHandler.检查这个类似的问题在SpringMVC中使用@ResponseBody返回JsonObject


小智 9

您可以尝试以下 get 和 post 方法

@Autowired
private MuffinRepository muffinRepository;

@Test
public void testGetMethod throws Exception(){
    Muffin muffin = new Muffin("Butterscotch");
    muffin.setId(1L);
    
    BddMockito.given(muffinRepository.findOne(1L)).
        willReturn(muffin);
        
    mockMvc.perform(MockMvcRequestBuilders.
        get("/muffins/1")).
        andExpect(MockMvcResutMatchers.status().isOk()).
        andExpect(MockMvcResutMatchers.content().string("{\"id\":1, "flavor":"Butterscotch"}"));    
}

//Test to do post operation
@Test
public void testPostMethod throws Exception(){
    Muffin muffin = new Muffin("Butterscotch");
    muffin.setId(1L);
    
    BddMockito.given(muffinRepository.findOne(1L)).
        willReturn(muffin);
        
    mockMvc.perform(MockMvcRequestBuilders.
        post("/muffins")
        .content(convertObjectToJsonString(muffin))
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(MockMvcResutMatchers.status().isCreated())
        .andExpect(MockMvcResutMatchers.content().json(convertObjectToJsonString(muffin))); 
}
Run Code Online (Sandbox Code Playgroud)

如果响应为空,请确保覆盖equals()您的存储库hashCode()Entity正在使用的方法:

//Converts Object to Json String
private String convertObjectToJsonString(Muffin muffin) throws JsonProcessingException{
    ObjectWriter writer = new ObjectWriter().writer().withDefaultPrettyPrinter();
    return writer.writeValueAsString(muffin);
}
Run Code Online (Sandbox Code Playgroud)


miP*_*der 7

有 2 种方法可以检查 JSON 响应。让我引导您完成这两个过程(从上面的问题中获取测试方法,并假设{"data":[{"useRegEx":"false","hosts":"v2v2v2"}]}上面给出的响应)

方法 1) 断言完整的 JSON

@Test
public final void testAlertFilterView() {       
    mockMvc.perform(get("/getServerAlertFilters/v2v2v2/")
           .contentType("application/json"))
           .andExpect(status().isOk())
           // you may even read bigger json responses from file and convert it to string, instead of simply hardcoding it in test class
           .andExpect(content().json("{"data":[{"useRegEx":"false","hosts":"v2v2v2"}]}"))     
}
Run Code Online (Sandbox Code Playgroud)

方法2)断言响应的特定键值(不编写多余的代码)

.andExpect(jsonPath("$.data[0].useRegEx").value(false))
.andExpect(jsonPath("$.data[0].hosts").value("v2v2v2"));
Run Code Online (Sandbox Code Playgroud)

您可能需要的另一件事是导入声明,

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
Run Code Online (Sandbox Code Playgroud)