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

问题描述 投票:27回答:3

这是我的控制器内部的方法,由@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,以便我可以完成我的测试用例。

java spring junit mocking spring-test-mvc
3个回答
17
投票

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

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

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

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


10
投票

406 Not Acceptable状态代码意味着Spring无法将对象转换为json。您可以让您的控制器方法返回一个字符串并执行return json.toString();或配置您自己的HandlerMethodReturnValueHandler。检查这个类似的问题Returning JsonObject using @ResponseBody in SpringMVC


1
投票

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

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

如果响应为空,请确保在您的存储库正在使用的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);
}
© www.soinside.com 2019 - 2024. All rights reserved.