Disable JMS consuming bean in unit-test

Viewed 3363

I've build a Spring application that receives JMS messages (@JmsListener). During development I'd like to send some messages to the JMS-queue the listener listens to, so I wrote a unit-test that sends some messages (JmsTemplate). In this unit-test I use @SpringBootTest and @RunWith(SpringRunner.class) in order to load the application context (beans for datasources etc).

However, when the unit-test starts, it also loads the jms listener bean which directly starts consuming my new messages.

I would like to disable this jms listener bean in this test scenario so that messages are just added to the queue. Then later, I can start the main application and watch them being consumed.

How should I approach this?

I guess I could also have asked how I could disable a bean in general.

Thanks in advance.

4 Answers

Instead of using profiles you can also achieve this with a property:

@ConditionalOnProperty(name = "jms.enabled", matchIfMissing = true)
public class JmsListenerBean {
    ...
}

The matchIfMissing attribute tells Spring to set this property to true by default. In your test class you can now disable the JmsListenerBean:

@TestPropertySource(properties = "jms.enabled=false")
public class MyTest {
    ...
}

I think you can do it by this code:-

private void stopJMSListener() {
    if (customRegistry == null) {
        customRegistry = context.getBean(JmsListenerEndpointRegistry.class);
    }
    customRegistry.stop();
}

private void startJMSListener() {
    if (customRegistry == null) {
        customRegistry = context.getBean(JmsListenerEndpointRegistry.class);
    }
    customRegistry.start();
}
Related