Reputation: 359
I am currently learning spring integration framework. So please forgive and correct me if my question is absurd. how to or is there a way to mock an http outbound gateway to run my unit tastcase?
public IntegrationFlow sendSms() {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
final JsonObjectMapper<?, ?> mapper = new Jackson2JsonObjectMapper(objectMapper);
return IntegrationFlows.from("sendSmsGatewayRequestChannel")
.handle(Http
.outboundGateway(environment.getProperty("integration.sms.endpoint")
+ "?ProductType={ProductType}&MobleNo={MobleNo}&smsType={smsType}&Message={Message}")
.expectedResponseType(String.class).httpMethod(HttpMethod.GET)
.uriVariableExpressions(createExpressionMap()))
.transform(Transformers.fromJson(SmsResponseDto.class, mapper)).get();
}
this is my integration flow.
Also, can we use mockmvc for testing inbound gateway?
Upvotes: 2
Views: 1404
Reputation: 359
add a bean id to the handler as,
@Bean
public IntegrationFlow sendSms() {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
final JsonObjectMapper<?, ?> mapper = new Jackson2JsonObjectMapper(objectMapper);
return IntegrationFlows.from("sendSmsGatewayRequestChannel")
.handle(Http.outboundGateway(smsEndpoint).expectedResponseType(String.class).httpMethod(HttpMethod.GET)
.uriVariableExpressions(createExpressionMap()), **e -> e.id("smsOutboundGateway")**)
.transform(Transformers.fromJson(SmsResponseDto.class, mapper)).get();
}
then you can mock the response by,
final ArgumentCaptor<Message<?>> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
final MessageHandler mockMessageHandler = MockIntegration.mockMessageHandler(messageArgumentCaptor)
.handleNextAndReply(m -> MessageBuilder.withPayload(
"response")
.build());
mockIntegrationContext.substituteMessageHandlerFor("smsOutboundGateway", mockMessageHandler);
Note: I am new to spring integration. so i don't know whether this is the correct way to do it. anyways, it's working :D. correct if i'm wrong. :)
Thanks Artem Bilan for the help.
Upvotes: 2
Reputation: 121542
Yes, any handle()
(or better to say MessageHandler
) in the application can be mocked. For this purpose we need an @SpringIntegrationTest
and MockIntegration
API.
See more info in the docs: https://docs.spring.io/spring-integration/docs/current/reference/html/testing.html#testing
And yes, with HTTP we really can use Mock MVC framework and its MockMvcClientHttpRequestFactory
to be injected into the HttpRequestExecutingMessageHandler
represented by that Http.outboundGateway()
.
See more in docs: https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#spring-mvc-test-client
Upvotes: 2