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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30482934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:42:35  来源:igfitidea点击:

How to check JSON in response body with mockMvc

javaspringjunitmockingspring-test-mvc

提问by Zeeshan

This is my method inside my controller which is annotated by @Controller

这是我的控制器中的方法,由 @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;
    }

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

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

And this is my JUnit 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();
        }
    }

Here is the console output:

这是控制台输出:

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

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

Evenresult.getResponse().getContentAsString()是一个空字符串。

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

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

采纳答案by Menuka Ishan

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

我使用 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'}]}"));
    }

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

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

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

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

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

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

回答by medvedev1088

The 406 Not Acceptablestatus code means that Spring couldn't convert the object to json. You can either make your controller method return a String and do return json.toString();or configure your own HandlerMethodReturnValueHandler. Check this similar question Returning JsonObject using @ResponseBody in SpringMVC

406 Not Acceptable状态代码表示春节不能将对象转换为JSON。您可以让您的控制器方法返回一个 String 并执行return json.toString();或配置您自己的HandlerMethodReturnValueHandler. 检查这个类似的问题Returning JsonObject using @ResponseBody in SpringMVC

回答by Nagaraj

You can try the below for get and post methods

您可以尝试以下获取和发布方法

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

If the response is empty then make sure to override equals()and hashCode()methods on the Entityyour repository is working with:

如果响应是空的,那么要确保覆盖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);
}