springBoot中“MockMvc”的进行Controller进行单元测试:application/octet-stream' not supported问题小结


解决方案:这个问题其实是Content-type的问题,只需要在相关的代码加入相关Content-type中就可以了,代码如下:

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM