【发布时间】:2021-09-13 16:49:35
【问题描述】:
我有一种情况,我正在为 IntegrationFlow 编写单元测试,该测试依赖于执行身份验证的配置 RestTemplate。
@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 之前,此测试似乎不会覆盖配置类上注入的 RestTemplate。
对此的任何想法将不胜感激。
【问题讨论】:
标签: mockito spring-integration junit5 spring-test