Image by Free-Photos from Pixabay

Testing transactional routes in Apache Camel can get tricky, especially if the test involves JMS queues or XA (two-phase commit) transactions. Tests may sometimes fail, even if we use NotifyBuilder to wait for the route to complete. In this article, I’ll show how to fix issues with the testing of transactional routes in Camel.

The complete code for this article is available on GitHub.

Problem with Testing Transactional Routes

Suppose we have a route that takes a message from the queue and puts it to the database. That’s a typical use case for XA transactions, provided you’ve set them up the right way, as I’ve described in this article. Wrapping this route in an XA transaction ensures that the message is neither lost nor duplicated.

In some cases, it’s enough to just use the NotifyBuilder class to wait until the message is processed by the route, based on some conditions. A typical example:

@Test
@Transactional
public void testSuccessWrong() {
    
    NotifyBuilder notify = new NotifyBuilder(camelContext)
            .from("activemq:TestQueue")
            .whenCompleted(1)
            .create();

    jmsTemplate.send("TestQueue", session -> session.createTextMessage("testtestte"));

    assertThat(notify.matches(10, TimeUnit.SECONDS)).isTrue();

    List<String> messages = jdbcTemplate.queryForList("select contents from message", String.class);

    assertThat(messages).hasSize(1);
    assertThat(messages.get(0)).isEqualTo("testtestte");
    
}

In this code, NotifyBuilder waits for some amount of messages originating from the activemq:TestQueue endpoint to complete successfully. The call notify.matches() blocks the test until this condition is true.

One of the important things here is to always assert that the result of notify.matches() call is true. This method may return false in case the condition wasn’t satisfied within the specified amount of time.

The problem with this code is that the message we send to the ActiveMQ queue gets processed in a different thread than the thread of the test. This means that the SQL select query executed by the jdbcTemplate.queryForList() will happen in a different transaction than the one where the message is inserted.

This SQL query may or may not return results, depending on whether the message transaction was already committed or not. We have a typical case of race condition, and the test may become unstable.

The test will most likely fail if we use XA transactions, as they typically take more time. To fix this, we’ll have to use route advices and transaction synchronization.

Using Route Advices and Transaction Synchronization

First, using route advices, we can inject an additional node to the route. In this case, we’ll add it as the first node of the route, using the weaveAddFirst() method:

AdviceWithRouteBuilder.adviceWith(camelContext, "queueRoute", context ->
    context.weaveAddFirst().process(exchange -> {
        // do something before exchange processing
    }
);

Now we’ll use Spring Transaction API to register a synchronization — a piece of code that will be executed after the transaction is committed:

TransactionSynchronizationManager.registerSynchronization(
        new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                // do something after transaction commit
            }
        }))

Finally, to unblock the test after the transaction is committed, we’ll use theCountDownLatch class from the standard Java library. Here’s how the complete code looks like:

// setting the latch to 1
CountDownLatch transactionLatch = new CountDownLatch(1);

// adding a node as the first node of the route
AdviceWithRouteBuilder.adviceWith(camelContext, "queueRoute", context ->
        context.weaveAddFirst().process(exchange ->
                // adding transaction synchronization
                TransactionSynchronizationManager.registerSynchronization(
                        new TransactionSynchronizationAdapter() {
                            @Override
                            public void afterCommit() {
                                // when the transaction is finished, count down the latch
                                transactionLatch.countDown();
                            }
                        }))

);

// sending the message to the queue
jmsTemplate.send("TestQueue", session -> session.createTextMessage("testtestte"));

// waiting until the latch becomes 0
assertTrue(transactionLatch.await(5, TimeUnit.SECONDS));

// now we may verify the database state
List<String> messages = jdbcTemplate.queryForList("select contents from message", String.class);

assertThat(messages).hasSize(1);
assertThat(messages.get(0)).isEqualTo("testtestte");

The call transactionLatch.await() will block the current thread (the thread of the test) until the latch becomes 0. When the message has finished processing, and the transaction is committed, the latch releases the current thread. At this point, it is safe to verify the state of the database.

The code for this article is available on GitHub.