Search code examples
spring-integrationspring-integration-dsl

How to invoke a channel in spring integration tests


I have a Flow which takes string input

  @Bean
  public IntegrationFlow myFlow() {
        // @formatter:off
        return IntegrationFlows.from("some.input.channel")
                               .handle(someService)
                               .get();

How do i invoke this from my integration test, how to put a string message on "some.input.channel"


Solution

  • Read Javadocs of the API you use:

    /**
     * Populate the {@link MessageChannel} name to the new {@link IntegrationFlowBuilder} chain.
     * The {@link org.springframework.integration.dsl.IntegrationFlow} {@code inputChannel}.
     * @param messageChannelName the name of existing {@link MessageChannel} bean.
     * The new {@link DirectChannel} bean will be created on context startup
     * if there is no bean with this name.
     * @return new {@link IntegrationFlowBuilder}.
     */
    public static IntegrationFlowBuilder from(String messageChannelName) {
    

    Then open a Reference Manual of the Framework you use:

    https://docs.spring.io/spring-integration/docs/current/reference/html/messaging-channels-section.html#messaging-channels-section

    https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#integration-testing-annotations-standard

    So, the channel created by the Java DSL becomes a bean in the application context. There is just enough to autowire it into the test class and call its send() from the test method:

    @RunWith(SpringRunner.class)
    @ContextConfiguration(classes = MyFlowConfiguration.class)
    public class IntegrationFlowTests {
    
        @Autowired
        @Qualifier("some.input.channel")
        private MessageChannel someInputChannel;
    
        @Test
        public void myTest() {
              this.someInputChannel.send(new GenericMessage<>("foo"));
        }
    }