如何使用mockMvc检查响应体中的JSON[英] How to check JSON in response body with mockMvc

本文是小编为大家收集整理的关于如何使用mockMvc检查响应体中的JSON的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

这是我的控制器内部的方法,由@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.

这是我的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();
        }
    }

这是控制台输出:

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

偶数result.getResponse().getContentAsString()是一个空字符串.

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

推荐答案

我将测试设备用于单元测试.但是在春季测试框架中,它们看起来都相似.所以我相信您的测试就像以下

@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")));

您可能会发现content().json()不是解决方案,请添加

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

其他推荐答案

406 Not Acceptable状态代码表示Spring无法将对象转换为JSON.您可以使您的控制器方法返回字符串并进行return json.toString();或配置自己的HandlerMethodReturnValueHandler.检查这个类似的问题 springmvc

其他推荐答案

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

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

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

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

本文地址:https://www.itbaoku.cn/post/978715.html

问题描述

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

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

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

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.

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

推荐答案

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

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

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

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

其他推荐答案

The 406 Not Acceptable status 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

其他推荐答案

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

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

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