1
votes

I'm trying to write a test case for a scenario in which I send a message to a JMS endpoint and then the message is processed using Spring Integration. Here is a test case that works but its not entirely clear to me why it works. Here is the test:

public class MessageListenerTest {

@Autowired ApplicationContext context;
@Test
public void testEventListener() {
    SubscribableChannel eventsChannel = (SubscribableChannel) context.getBean("events");
    class TestMessageHandler implements MessageHandler {
        public Boolean received = false;
        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            received = true;
        } 
    }
    TestMessageHandler handler = new TestMessageHandler();
    eventsChannel.subscribe(handler);
    PollableChannel outputChannel = new QueueChannel();
    PollingConsumer consumer = new PollingConsumer(outputChannel, handler);
    consumer.setBeanFactory(context);
    consumer.start();
    String msg = "hello world!";
    JmsTemplate template = (JmsTemplate) context.getBean("jmsTemplate");
    template.convertAndSend("myQueue", msg);
    outputChannel.receive(2000);
    Assert.assertTrue(handler.received);
}
}

This tests that the message sent to the queue is received. The message is received by a SubscribableChannel named events. What is not clear to me is how the PollableChannel is connected to the SubscribableChannel. Is it because of TestMessageHandler? If so, how? If this is working entirely by accident, it would be useful if someone could fix this or provide a simpler test case for this scenario.

UPDATE: Based on the suggestions in the comments, here is a modified test case:

public class MessageListenerTest {

@Autowired ApplicationContext context;

@Test
public void testEventListener() throws InterruptedException {
    SubscribableChannel eventsChannel = (SubscribableChannel) context.getBean("events");
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    MessageHandler handler = new MessageHandler() {
        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            countDownLatch.countDown();
        } 
    };
    eventsChannel.subscribe(handler);
    String msg = "hello world!";
    JmsTemplate template = (JmsTemplate) context.getBean("jmsTemplate");
    template.convertAndSend("myQueue", msg);
    Assert.assertTrue(countDownLatch.await(2, TimeUnit.SECONDS));
}
}
1

1 Answers

1
votes

Your outputChannel just doesn't work. This channel is a test-case scope. so no one sends messages to it.

You can check that with the assert:

Assert.notNull(outputChannel.receive(2000));

It doesn't matter for how much channel the MessageHandler is subscribed. It just handles messages. So, it continues to handle messages from your events. And the binding to that inline outputChannel just is dead and doesn't matter for other application.