Disable JMS bean usage in unit test

I have created a Spring application that receives JMS ( @JmsListener

) messages . During development, I would like to send some messages to the JMS queue that the listener is listening on, so I wrote a block test that sends some messages ( JmsTemplate

). This unit test I use @SpringBootTest

and @RunWith(SpringRunner.class)

to download an application context (beans for data sources, etc.).

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

I want to disable this jms listener bean in this test scenario so that messages are just added to the queue. Then I can run the main application and see how they are consumed.

How do I approach this?

I guess I might as well ask how to disable the bean altogether.

Thanks in advance.

+4


source to share


4 answers


To fix this problem, you can use profiles .

Add annotation to your listener @Profile

:

@Profile("!test-without-jmslistener")
public class JmsListenerBean {
    ...
}

      

This tells Spring that it should only instantiate this bean if the "test-without-jmslistener" profile is not active (the exclamation mark negates the condition).



In your unit test class, the following annotation is added:

@ActiveProfiles("test-without-jmslistener)
public class MyTest {
    ...
}

      

Now the Spring test runner will activate this profile before running your tests and Spring will not load your bean.

+6


source


Another solution to this problem: add @ComponentScan()

to the test class to skip loading the specified beans.

@SpringBootTest
@RunWith(SpringRunner.class)
@ComponentScan(basePackages="com.pechen.demo", excludeFilters=@Filter(type=FilterType.ASSIGNABLE_TYPE, classes=JmsListener.class))
public class MyTest(){

}

      



See spring component checking includes and excludes filters for more details .

0


source


I think you can do it with 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();
}

      

0


source


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 {
    ...
}

      

0


source







All Articles