You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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逻辑能触发:

  1. 导入ArgumentMatchers类:
import static org.mockito.ArgumentMatchers.any;
  1. 替换原有的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 23:15:55