JUnit5 MockMvc测试REST Controller POST接口返回空Body问题求助
问题原因
- 核心原因:测试类中
FieldsToMapConverter<ResponseDetails>是通过@MockBean注入的模拟对象,你没有为该对象的getFieldsAsMap方法配置调用返回规则,Mockito默认会对Mock对象的Map类型返回值返回空Map,对应你日志里看到的{}空响应体。 - 潜在问题:当前测试用的
jsonPath("$.id")路径不匹配实际返回结构,Controller返回的外层结构包含message、data、location三个字段,id存储在data属性下,正确路径应为$.data.id。
解决建议
- 为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);
- 修正jsonPath校验逻辑,注意匹配id的类型:
.andExpect(jsonPath("$.data.id", is(1)))
- 可选优化:如果
FieldsToMapConverter的实现逻辑简单、无复杂依赖,可以在测试中注入真实的实现类而非Mock对象,省略手动配置Mock返回的步骤,更贴近真实运行逻辑。
内容的提问来源于stack exchange,提问作者Piotr Głowacki
相关产品推荐
相关产品推荐

