MockMvc单元测试
背景
1、使用 Squaretest 生成controller的测试类(略)
生成的代码大概如下:
该文章只简单记录使用的一个过程,和遇到过的一个小问题,
就是,requestbody 传参无效
import com.alibaba.fastjson.JSON; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.reflections.Reflections.log; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @RunWith(SpringRunner.class) @WebMvcTest(TaskController.class) public class TaskControllerTest { @Autowired private MockMvc mockMvc; @Test public void testDataHis() throws Exception { // Setup HisFo hisFo = new HisFo(); hisFo.setId("222222"); hisFo.setCode("linye"); log.info("fo: {}", JSON.toJSONString(hisFo)); // Run the test final MockHttpServletResponse response = mockMvc.perform( post("/v1/task/biz-data/history") .content(JSON.toJSONString(hisFo)).contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON_UTF8)) .andReturn().getResponse(); // Verify the results assertEquals(HttpStatus.OK.value(), response.getStatus()); String contentAsString = response.getContentAsString(); log.info("bizData his: {}", contentAsString); assertNotNull(JSON.parseObject(contentAsString).getJSONObject("data")); } }
问题描述:
1、这个接口的参数 hisFo, 它的两个属性都是必填的,一开始,只写了 id 的值,就报错:
FlashMap: Attributes = null MockHttpServletResponse: Status = 400 Error message = null Headers = {} Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = [] java.lang.AssertionError: Expected :200 Actual :400 <Click to see difference>
只告诉我,400了,但也没有更多的有效报错。
一开始,还以为参数没有传好,没有接收到。。。在捣鼓 “mockMvc 如何传参” 找了很久,但发现写法就是没有问题。
后来才知道, 原来参数没有传好,这里是看不到原因的。。。当然controller 那里也没有进入,所以一开始有一点点疑惑。
再做一点点笔记: mockMvc 如何传参 mockMvc.perform( post("/v1/task/biz-data/history") .content(JSON.toJSONString(hisFo)) .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON_UTF8)) .content(JSON.toJSONString(hisFo)) // 这个就是传参。。。把对象转 jsonstring 就行。。。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南