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

使用Http.outboundGateway的Spring Integration流测试如何Mock注入的RestTemplate

问题根因
  • 你的测试写法中@Autowired会先触发Spring容器初始化XXIntegrationConfig实例,此时容器会注入真实的RestTemplate实例,后续@InjectMocks的Mock注入逻辑完全不会生效,自然配置类里用到的还是真实对象。
  • 手动调用xxIntegrationConfig.enrichSecondary()拿到的消费器,内部捕获的还是配置类初始化时注入的真实RestTemplate,而非你创建的Mock对象。
可行解决方案

用Spring Boot提供的@MockBean注解替换容器中的原生RestTemplate,该注解会在Spring上下文初始化阶段就将Mock对象注册进容器,所有依赖RestTemplate的Bean都会自动注入这个Mock实例,不需要手动操作配置类的依赖注入。

修改后的测试代码示例

@SpringBootTest
@SpringIntegrationTest
public class XXIntegrationConfigTests {
    // 用@MockBean替换容器中所有RestTemplate依赖
    @MockBean
    private RestTemplate restTemplate;

    // 直接注入容器管理的IntegrationFlow,也可以按你需要注入enrichSecondary的Bean
    @Autowired
    private IntegrationFlow readRemote;

    @Autowired
    private IntegrationFlowContext integrationFlowContext;

    @Test
    public void testEnrichSecondary() {
        // 按你的实际请求参数写匹配规则,这里示例匹配两次GET请求
        // 匹配第一个主接口请求
        when(restTemplate.exchange(
                ArgumentMatchers.eq("http://localhost:8080/main/xx-001"),
                ArgumentMatchers.eq(HttpMethod.GET),
                ArgumentMatchers.any(HttpEntity.class),
                ArgumentMatchers.eq(String.class)
        )).thenReturn(new ResponseEntity("{\"id\":\"xx-001\",\"name\":\"test\"}", HttpStatus.OK));
        // 匹配secondary接口请求
        when(restTemplate.exchange(
                ArgumentMatchers.eq("http://localhost:8080/main/xx-001/secondary"),
                ArgumentMatchers.eq(HttpMethod.GET),
                ArgumentMatchers.any(HttpEntity.class),
                ArgumentMatchers.eq(String.class)
        )).thenReturn(new ResponseEntity("{\"value\":\"secondary test data\"}", HttpStatus.OK));

        // 注册流(如果是测试完整readRemote流也可以直接用它的实例发请求)
        IntegrationFlowContext.IntegrationFlowRegistration flowRegistration =
                integrationFlowContext.registration(readRemote).register();

        final Message<?> request =
                MessageBuilder.withPayload(new HashMap<String,Object>())
                        .setHeader("mainId", "xx-001")
                        .build();

        Message<?> response = 
                flowRegistration.getMessagingTemplate().sendAndReceive(request); 
        // 这里加断言验证返回结果即可
    }
}
补充说明

如果只需要单独测试enrichSecondary子逻辑,不需要加载完整的readRemote流,也可以直接注入容器管理的Consumer<EnricherSpec>实例,该实例内部用到的RestTemplate已经是你通过@MockBean替换的Mock对象,直接构造子流测试即可。

内容的提问来源于stack exchange,提问作者Dave G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:30:03