Spring Boot集成测试@MockMvc返回空响应体问题排查求助
MockMvc测试响应体为空的问题分析与解决
核心原因
测试中Mockito的参数匹配逻辑导致PlanetService.create()返回null,最终Controller的响应体为空。
具体来说,你在测试中写了:
when(planetService.create(planet)).thenReturn(planet);
这里Mockito会严格匹配传入的planet实例,但Spring MVC处理请求时,会通过RequestBody将JSON反序列化为全新的Planet对象,和你测试中创建的planet不是同一个实例,因此Mock的匹配条件不生效,create()方法默认返回null。Controller将null作为响应体返回,就出现了控制台中Body = 空的情况。
解决办法
修改Mockito的参数匹配方式,使用any(Planet.class)匹配任意Planet类型的参数,确保Mock逻辑能触发:
- 导入ArgumentMatchers类:
import static org.mockito.ArgumentMatchers.any;
- 替换原有的when语句:
// 原代码 // when(planetService.create(planet)).thenReturn(planet); // 修改后 when(planetService.create(any(Planet.class))).thenReturn(planet);
这样无论Spring MVC传入哪个Planet实例,Mock都会返回你预设的planet对象,Controller就能将其序列化为JSON作为响应体返回,jsonPath断言也能正常匹配。
额外检查点
- 确保
Planet实体类的所有字段都有public的getter方法(你的代码中已满足),Jackson需要通过getter来序列化对象为JSON。 - 测试类的
@WebMvcTest可以指定具体Controller类,优化上下文加载:
@WebMvcTest(PlanetController.class)
内容的提问来源于stack exchange,提问作者Luis Felipe Gongora Garcia
相关产品推荐
相关产品推荐

