Warm tip: This article is reproduced from serverfault.com, please click

how to mock outbound gateways in spring integration

发布于 2020-11-30 13:25:23

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?

Questioner
Sanal M
Viewed
0
Sanal M 2020-12-07 15:39:58

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.