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

这是我的控制器内部的方法,由@Controller注释

 @RequestMapping(value = "/getServerAlertFilters/{serverName}/", produces = "application/json; charset=utf-8") @ResponseBody public JSONObject getServerAlertFilters(@PathVariable String serverName) { JSONObject json = new JSONObject(); List 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,以便我可以完成我的测试用例。

406 Not Acceptable状态代码表示Spring无法将对象转换为json。 你可以让你的控制器方法返回一个字符串并return json.toString(); 或配置您自己的HandlerMethodReturnValueHandler 。 检查这个类似的问题在SpringMVC中使用@ResponseBody返回JsonObject

我使用TestNG进行unit testing。 但在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密钥和值,你可以使用jsonpath .andExpect(jsonPath("$.yourKeyValue", is("WhatYouExpect")));

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

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

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

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

如果响应为空,那么请确保在您的存储库正在使用的Entity上重写equals()hashCode()方法:

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