You need to enable JavaScript to run this app. JUnit5 MockMvc测试REST Controller POST接口返回空Body问题求助
优惠活动
大模型
产品
解决方案
定价
更多

JUnit5 MockMvc测试REST Controller POST接口返回空Body问题求助

问题原因

  • 核心原因:测试类中FieldsToMapConverter<ResponseDetails>是通过@MockBean注入的模拟对象,你没有为该对象的getFieldsAsMap方法配置调用返回规则,Mockito默认会对Mock对象的Map类型返回值返回空Map,对应你日志里看到的{}空响应体。
  • 潜在问题:当前测试用的jsonPath("$.id")路径不匹配实际返回结构,Controller返回的外层结构包含message、data、location三个字段,id存储在data属性下,正确路径应为$.data.id。

解决建议

  1. 为Mock的FieldsToMapConverter配置返回规则,示例代码如下:
// 构造你期望返回的响应结构
Map<String, Object> expectedResponse = new HashMap<>();
expectedResponse.put("message", MessageContent.OK);
expectedResponse.put("data", Collections.singletonMap("id", 1L));
expectedResponse.put("location", URI.create("http://localhost/customers/1"));
// 配置Mock方法的返回值
when(fieldsToMapConverter.getFieldsAsMap(any(ResponseDetails.class))).thenReturn(expectedResponse);
  1. 修正jsonPath校验逻辑,注意匹配id的类型:
.andExpect(jsonPath("$.data.id", is(1)))
  1. 可选优化:如果FieldsToMapConverter的实现逻辑简单、无复杂依赖,可以在测试中注入真实的实现类而非Mock对象,省略手动配置Mock返回的步骤,更贴近真实运行逻辑。

内容的提问来源于stack exchange,提问作者Piotr Głowacki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 21:36:03