zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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