使用 Http.outboundGateway() 和已配置的 RestTemplate 测试 spring-集成流程

Testing spring-integration flow using Http.outboundGateway() with configured RestTemplate

我遇到这样一种情况,我正在为依赖于执行身份验证的配置 RestTemplate 的 IntegrationFlow 编写单元测试。

@Configuration
public class XXIntegrationConfig {
    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public IntegrationFlow readRemote() {
        return f ->
            f.handle(
                Http.outboundGateway("http://localhost:8080/main/{mainId}", restTemplate)
                    .httpMethod(HttpMethod.GET)
                    .uriVariable("mainId", "headers.mainId")
                    .expectedResponseType(String.class)
            )
            .transformers(Transformers.fromJson())
            .enrich(enrichSecondary())
            .transform(Transformers.toJson());
    }

    @Bean
    public Consumer<EnricherSpec> enrichSecondary() {
        return e ->
            e.requestSubFlow(
                esf -> esf.handle(
                    Http.outboundGateway("http://localhost:8080/main/{mainId}/secondary", restTemplate)
                        .httpMethod(HttpMethod.GET)
                        .uriVariable("mainId", "headers.mainId")
                        .mappedResponseHeaders()
                        .expectedResponseType(String.class)
                )
                .transform(Transformers.fromJson())
            )
            .propertyExpression("secondary", "payload.value");
    }
}

我很难建立 restTemplate@Autowired 是 Mock 的测试。

我试过类似下面的方法但没有成功

@SpringBootTest
@SpringIntegrationTest
public class XXIntegrationConfigTests {
    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    @Autowired
    private XXIntegrationConfig xxIntegrationConfig;

    @Autowired
    private IntegrationFlowContext integrationFlowContext;

    @Test
    public void testEnrichSecondary() {
        when(restTemplate.exchange(..... arg matchers ....)).thenReturn(
              new ResponseEntity("test document", HttpStatus.OK)
        );

        final Consumer<EnricherSpec> enrichSecondary = xxIntegrationConfig.enrichSecondary();
        IntegrationFlow flow =
            f -> f.enrich(enrichSecondary());
        IntegrationFlowContext.IntegrationFlowRegistration flowRegistration =
            integrationFlowContext.registration(flow).register();

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

        Message<?> response = 
                flowRegistration.getMessagingTemplate().sendAndReceive(request); 
    }
}

XXIntegrationConfig.

中构建 bean 之前,此测试似乎没有覆盖配置 class 上注入的 RestTemplate

如有任何想法,我们将不胜感激。

参见 Spring 引导的 @MockBeanhttps://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications.mocking-beans。因此,您需要的只是在测试中使用此注释标记您的 RestTemplate 属性,Spring Boot 将在预期配置中为您处理注入。