springBoot中“MockMvc”的进行Controller进行单元测试:application/octet-stream' not supported问题小结
SpringBoot 进行 not 39 小结 application 单元测试
2023-09-27 14:24:47 时间
解决方案:这个问题其实是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
相关文章
- SpringBoot系列之注解@Autowired VS @Qualifier VS @Primary(五)
- SpringBoot使用swagger2构建API文档
- SpringBoot添加定时任务
- SpringBoot 简介
- SpringBoot实现电子文件签字+合同系统!
- SpringBoot中使用Spring profile进行配置【谨慎使用,参见SpringBoot 2.4.0发布文档】
- SpringBoot+Vue前端Http调用后台封装POI接口导出EXCEL
- 【问题解决】SpringBoot工程无法找到父依赖 parent-pom Failure to find com.xxx:parent-pom:pom:1.0.0.RELEASE
- SpringBoot热重启配置
- SpringBoot:Maven创建一个HelloWorld
- SpringBoot继承第三方发送手机短信验证码
- SpringBoot集成JPA根据实体类自动生成表