解决方案:这个问题实际上是Content-type的问题,只须要在相关的代码加入相关Content-type中就能够了,代码以下:java
mockMvc.perform(post("/user") // 路径 .contentType(MediaType.APPLICATION_JSON) //用contentType表示具体请求中的媒体类型信息,MediaType.APPLICATION_JSON表示互联网媒体类型的json数据格式(见备注)。以前忘记设置了 .content(example) .accept(MediaType.APPLICATION_JSON)) //accept指定客户端可以接收的内容类型 .andExpect(content().contentType("application/json;charset=UTF-8")) //验证响应contentType == application/json;charset=UTF-8 .andExpect(jsonPath("$.id").value(1)) //验证id是否为1,jsonPath的使用 .andExpect(jsonPath("$.name).value("kqzhu"); // 验证name是否等于Zhukeqian String errorExample = "{"id":1, "name":"kqzhu"}"; MvcResult result = mockMvc.perform(post("/user") .contentType(MediaType.APPLICATION_JSON) .content(errorExample) .accept(MediaType.APPLICATION_JSON)) //执行请求 .andExpect(status().isBadRequest()) //400错误请求, status().isOk() 正确 status().isNotFound() 验证控制器不存在 .andReturn(); //返回MvcResult