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

2022-01-08 00:00:00 mocking spring java junit spring-test-mvc

这是我在控制器中的方法,由 @Controller

This is my method inside my controller which is annotated by @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;
    }

我期待 {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} 作为我的 json.

I am expecting {"data":[{"useRegEx":"false","hosts":"v2v2v2"}]} as my json.

这是我的 JUnit 测试:

And this is my JUnit test:

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

这是控制台输出:

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

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

Even result.getResponse().getContentAsString() is an empty string.

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

Can someone please suggest how to get my JSON in my JUnit test method so that I can complete my test case.

推荐答案

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

I use TestNG for my unit testing. But in Spring Test Framework they both looks similar. So I believe your test be like below

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

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

If you want check check json Key and value you can use jsonpath .andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));

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

You might find thatcontent().json() are not solveble please add

导入静态 org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

相关文章