How to test Apache Camel JMS routes with Spring and ActiveMQ step by step

Let’s assume we have a message redelivery Camel route which is reading messages from the dead letter queue, checks the amount of redelivery attempts and decides if the message should be send to the destination queue or not.

The Camel route

The route reads messages form the ActiveMQ dead letter queue and using the processor decides whether send it to the destination queue again or stop processing the route. We are using here Event Message from Enterprise Integration Patterns by implementing Camel “InOnly” Exchange Pattern in order to send the message to the destination queue.

The processor

In the processor we are obtaining header from the exchange object. The header keeps redelivery counter. If the counter reached the maximum number of redelivery attempts, we are stopping the route, otherwise we are incrementing the counter. We must set the counter to zero in the header just before sending the message for the first time.

Steps to test the route using JUnit

One way of unit testing Spring and Apache Camel is to extend CamelSpringTestSupport class. For more information please visit documentation concerning Camel Spring Testing. You can find there other ways of testing Camel with Spring.

Next step is to provide implementation of Spring Application Context and create context configuration using ActiveMQ configuration and the route we want to test. The route will be automatically added to the Camel Context as well.

When we created context configuration, we may go to the next step of writing our tests. First, let’s create a mock endpoint which will replace real dead letter queue endpoint from(jms:deadLetterQueue) with the mocked one. It will also intercept sending the message to the jms:destinationQueue. After interception we will add a test body text to our exchange. To achieve it, we will use AdviceWithRouteBuilder class. Having set the test body we may check in the test if our message reached the end of the route.

Now we can write unit tests. Let’s write two tests. One will be testing the whole route starting from receiving the message from dead letter queue, then incrementing the redelivery counter in the processor and finally sending the message to the destination queue. The second unit test will be checking the case when redelivery counter reached the maximum numbers of redelivery attempts and the route will be stopped.

Please note we are sending our test message to the mocked endpoint direct:deadLetterQueueMock instead of to the jms:deadLetterQueue.

The whole code can be found in my GitHub repository. Checkout it, run the tests and comment :-). I wish you green bars!

Software Developer. Java enthusiast.

Software Developer. Java enthusiast.