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));
}
}