Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing code that sends JMS messages

I have a class that after it does some stuff, sends a JMS message. I'd like to unit test the "stuff", but not necessarily the sending of the message.

When I run my test, the "stuff" green bars, but then fails when sending the message (it should, the app server is not running). What is the best way to do this, is it to mock the message queue, if so, how is that done.

I am using Spring, and "jmsTemplate" is injected, along with "queue".

like image 520
bmw0128 Avatar asked Dec 02 '08 22:12

bmw0128


People also ask

What is JMS testing?

Use the generic JMS plug-in to connect Rational® Integration Tester to a wide range of EAI platforms, which includes any vendor that provides an implementation of this Java™ standard. JMS provides a way of separating the application from the transport layer of providing data.

What is JUnit test code?

The JUnit test case is the set of code that ensures whether our program code works as expected or not. In Java, there are two types of unit testing possible, Manual testing and Automated testing. Manual testing is a special type of testing in which the test cases are executed without using any tool.


2 Answers

The simplest answer I would use is to stub out the message sending functionality. 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 obscures the sendMessage behavior. For example:

@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 is stubbed out or obscured is substantial, I would not use an anonymous inner class but just a "normal" inner class.

like image 107
Alex B Avatar answered Oct 25 '22 22:10

Alex B


You can inject a mocked jmsTemplate.

Assuming easymock, something like

JmsTemplate mockTemplate = createMock(JmsTemplate.class)

That would do the trick.

like image 23
tunaranch Avatar answered Oct 25 '22 22:10

tunaranch