Unit Testing Code That Sends JMS Messages

I have a class that, after it does something, sends a JMS message. I would like to unit test "stuff", but not necessarily sending a message.

When I run my test, the โ€œgreenโ€ green bars, but then I canโ€™t send a message (it should, the application server is not working). What is the best way to do this so that it makes fun of the message queue, if so, how to do it.

I use Spring, and "jmsTemplate" is entered along with the "queue".

+4
source share
5 answers

The simplest answer I would like to use is to drown out the functionality of sending messages. For example, if you have this:

public class SomeClass { public void doit() { //do some stuff sendMessage( /*some parameters*/); } public void sendMessage( /*some parameters*/ ) { //jms stuff } } 

Then I would write a test that hides the behavior of sendMessage. For instance:

 @Test public void testRealWorkWithoutSendingMessage() { SomeClass thing = new SomeClass() { @Override public void sendMessage( /*some parameters*/ ) { /*do nothing*/ } } thing.doit(); assertThat( "Good stuff happened", x, is( y ) ); } 

If the amount of code that was stubbed or obscured is substantial, I would not use an anonymous inner class, but simply a โ€œnormalโ€ inner class.

+8
source

You can enter mocked jmsTemplate.

Assuming easymock, something like

 JmsTemplate mockTemplate = createMock(JmsTemplate.class) 

That would do the trick.

+6
source

Another option is MockRunner, which provides dummy environments for JDBC, JMS, JSP, JCA, and EJB. This allows you to define queues / threads in the same way as in the โ€œrealโ€ case, and just send a message.

+1
source

Regarding how to organize all these test stubbing / mocks in a larger application ...

We create and maintain a larger enterprise application that is configured with Spring. This application runs as an EAR on JBoss Appserver. We defined our Spring context with beanRefFactory.xml

 <bean id="TheMegaContext" class="org.springframework.context.support.ClassPathXmlApplicationContext"> <constructor-arg> <list> <value>BasicServices.xml</value> <value>DataAccessBeans.xml</value> <value>LoginBeans.xml</value> <value>BussinessServices.xml</value> .... </list> </constructor-arg> </bean> 

To run unit tests, we simply use another beanRefFactory.xml, which exchanges basic services to use the test version. Within this test version, we can define beans with the same names as in the production version, but with a layout / stub or any other implementation (for example, the database uses the local Apache DPCP data source, and the production version uses the data source from the Application Server )

0
source

This is an ideal candidate for using jMock unit testing since your server is down, but you will use jMock to simulate server interaction.

0
source