Search code examples
springjunitspring-integration

Wait for ExecutorChannel to finish in junit


I am using spring integration and junit.

@Test
public void testOnePojo() throws Exception {
    ExecutorChannel orderSendChannel = 
    context.getBean("validationChannel", ExecutorChannel.class);
    ExecutorChannel orderReceiveChannel = context.getBean("auditChannel", ExecutorChannel.class);
    orderReceiveChannel.subscribe(t -> {
         System.out.println(t);//I want to see this output     
    }); 
    orderSendChannel.send(getMessageMessage());
}

I cannot see the output from the receiving channel. JUnit exits after subscribing. It there a proper way to wait inside testOnePojo until auditChannel receives a response.


Solution

  • you can use a CoundDownLatch in your test and wait for the MessageHandler to handle your message. Your example would look something like this:

    @Test
    public void testOnePojo() throws Exception {
        final CountDownLatch countDownLatch = new CountDownLatch(1);
    
        ExecutorChannel orderSendChannel =
            context.getBean("validationChannel", ExecutorChannel.class);
        ExecutorChannel orderReceiveChannel = context.getBean("auditChannel", ExecutorChannel.class);
        orderReceiveChannel.subscribe(t -> {
            System.out.println(t);//I want to see this output
            countDownLatch.countDown();
        });
        orderSendChannel.send(getMessageMessage());
    
        countDownLatch.await();
    }