Testing Camel routes: mocks, advice and timing

A Camel route is mostly wiring, and wiring breaks in ways the compiler cannot see: a wrong endpoint, a missing end(), a header that is never set. Camel ships test support built for that. This page explains how mock endpoints record and check messages, then runs real JUnit 6 tests with Camel 4.23, from CamelTestSupport and AdviceWith to timing traps with asynchronous routes and a Spring Boot test.

Contents

How Camel route tests work

Unit tests for plain Java call a method and check what it returns. A route has no return value of its own: it takes a message from an endpoint and sends results to other endpoints, often on other threads. Testing it means three things: start the route in a real CamelContext, feed it messages, and check what arrives at its outputs. Camel's test kit provides a tool for each step:

  • Mock endpoints: a mock: endpoint records every exchange it receives and checks it against expectations set beforehand, such as a message count, bodies or headers.
  • CamelTestSupport: a JUnit base class in camel-test-junit5 that creates a fresh CamelContext for each test, adds your routes, and gives you a ProducerTemplate.
  • AdviceWith: changes a route before it starts, so that a route reading from Kafka and writing to JMS can be tested with direct and mock endpoints instead, without editing the route.
  • NotifyBuilder: waits until a given number of exchanges have finished, for routes whose outputs you do not want to mock.
Camel test modules
ModuleMain typesBest for
camel-mock (comes with camel-core)MockEndpointRecording and checking messages, in any kind of test
camel-test-junit5CamelTestSupport, AdviceWithFast tests of routes without Spring
camel-test-spring-junit5@CamelSpringBootTest, @MockEndpointsAndSkipRoutes in a Spring Boot application, with its configuration
camel-coreNotifyBuilderWaiting for asynchronous routes to finish

The examples use Camel 4.23, JUnit 6.0 and Java 21. Each test class has a main method that runs it with the JUnit Platform launcher and prints one line per test, so the page shows real results; in a project, Maven or Gradle runs the same classes. The logging configuration replaces exchange ids, which change on every run, with <id>.

Mock endpoint expectations

A mock endpoint is useful even without JUnit. This program routes orders by size and checks the result twice, once with correct expectations and once with a deliberately wrong one, to show what a failure says:

Java
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;

public class MockExpectations {

    static class Routes extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:orders")
                .choice()
                    .when(simple("${body} > 100")).setHeader("priority", constant("high"))
                    .otherwise().setHeader("priority", constant("normal"))
                .end()
                .to("mock:accepted");
        }
    }

    public static void main(String[] args) throws Exception {
        CamelContext camel = new DefaultCamelContext();
        camel.addRoutes(new Routes());
        camel.start();
        ProducerTemplate template = camel.createProducerTemplate();
        MockEndpoint accepted = camel.getEndpoint("mock:accepted", MockEndpoint.class);

        accepted.expectedMessageCount(2);
        accepted.expectedBodiesReceived(250, 40);
        accepted.message(0).header("priority").isEqualTo("high");
        accepted.message(1).header("priority").isEqualTo("normal");
        template.sendBody("direct:orders", 250);
        template.sendBody("direct:orders", 40);
        accepted.assertIsSatisfied();
        System.out.println("first run: all expectations met, received "
            + accepted.getReceivedCounter());

        accepted.reset();
        accepted.expectedBodiesReceived(250, 40);
        accepted.message(1).header("priority").isEqualTo("high");
        template.sendBody("direct:orders", 250);
        template.sendBody("direct:orders", 40);
        try {
            accepted.assertIsSatisfied();
        } catch (AssertionError e) {
            System.out.println("second run: "
                + e.getMessage().replaceAll("[0-9A-F]{15}-[0-9A-F]{16}", "<id>"));
        }
        camel.stop();
    }
}
Output
first run: all expectations met, received 2
second run: Assertion error at index 1 on mock mock://accepted with predicate: header(priority) == high evaluated as: normal == high on Exchange[<id>]
  • The first run set four expectations: two messages, the bodies 250 and 40 in that order, and the priority header of each. assertIsSatisfied() checked them all and passed.
  • After reset(), the second run expected message 1 to have priority high. The failure names the message index, the predicate and what it evaluated to: normal == high.

Expectations must be set before the messages are sent, because the mock counts arrivals against them as they come in. assertIsSatisfied() then waits until the expected count has arrived, for up to 10 seconds by default, so a test that expects a message which never comes takes 10 s to fail. Change the wait with setResultWaitTime. Other common expectations are expectedHeaderReceived, expectedBodiesReceivedInAnyOrder, expectedMinimumMessageCount and message(i).body().contains(...).

A JUnit test with CamelTestSupport

A test class that extends CamelTestSupport returns its routes from createRouteBuilder() and gets a started context, a template and getMockEndpoint(...). The route under test filters orders and turns their quantity into an order id. The fourth test fails on purpose, to show the report:

Java
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.platform.engine.discovery.DiscoverySelectors;

public class OrderRouteTest extends CamelTestSupport {

    @Override
    protected RoutesBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from("direct:orders")
                    .filter(simple("${body} > 0"))
                        .transform(simple("order-${body}"))
                        .to("mock:accepted");
            }
        };
    }

    @Test
    void acceptsPositiveQuantities() throws Exception {
        MockEndpoint accepted = getMockEndpoint("mock:accepted");
        accepted.expectedBodiesReceived("order-3", "order-7");
        template.sendBody("direct:orders", 3);
        template.sendBody("direct:orders", 7);
        MockEndpoint.assertIsSatisfied(context);
    }

    @Test
    void dropsZeroQuantity() throws Exception {
        getMockEndpoint("mock:accepted").expectedMessageCount(0);
        template.sendBody("direct:orders", 0);
        MockEndpoint.assertIsSatisfied(context);
    }

    @Test
    void repliesWithTheOrderId() {
        assertEquals("order-5", template.requestBody("direct:orders", 5));
    }

    @Test
    void failingOnPurposeToShowTheReport() throws Exception {
        getMockEndpoint("mock:accepted").expectedBodiesReceived("order-1");
        template.sendBody("direct:orders", 2);
        MockEndpoint.assertIsSatisfied(context);
    }

    public static void main(String[] args) {
        TestExecutionListener printer = new TestExecutionListener() {
            @Override
            public void executionFinished(TestIdentifier id, TestExecutionResult result) {
                if (id.isTest()) {
                    System.out.println(result.getStatus() + "  " + id.getDisplayName()
                        + result.getThrowable().map(t -> "\n    " + t.getMessage()).orElse(""));
                }
            }
        };
        LauncherFactory.create().execute(LauncherDiscoveryRequestBuilder.request()
            .selectors(DiscoverySelectors.selectClass(OrderRouteTest.class)).build(), printer);
    }
}
Output
WARN  [main] MockEndpoint - Received exchange: Exchange[<id>]
WARN  [main] MockEndpoint - Received exchange message: Message
WARN  [main] MockEndpoint - Received exchange message body: order-2
WARN  [main] MockEndpoint - Received exchange message body type: class java.lang.String
FAILED  failingOnPurposeToShowTheReport()
    mock://accepted Body of message: 0. Expected: <order-1> but was: <order-2>
SUCCESSFUL  dropsZeroQuantity()
SUCCESSFUL  acceptsPositiveQuantities()
SUCCESSFUL  repliesWithTheOrderId()
  • Three tests passed: positive quantities reached the mock as order-3 and order-7, zero was filtered out, and requestBody returned order-5 directly, which needs no mock at all.
  • The failing test expected order-1 but received order-2. The assertion message says exactly that, and before failing the mock logged the exchange it received, with its body and body type, at WARN.
  • The tests ran in an order chosen by JUnit, not the order in the file. Each one got a new CamelContext, so no state leaked between them.

MockEndpoint.assertIsSatisfied(context) checks every mock in the context at once. A new context per test is the safe default; for slow route setups, @TestInstance(Lifecycle.PER_CLASS) reuses one context for all tests in the class, and then each test must call reset() on the mocks it uses.

Rewiring a production route with AdviceWith

Real routes start from Kafka or JMS and call HTTP services, none of which a unit test should touch. AdviceWith changes the route in the test only. This route reads from a Kafka topic, calls a pricing service and sends to a JMS queue, and no Kafka, HTTP or JMS component is on the classpath:

Java
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.AdviceWith;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelContextConfiguration;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.apache.camel.test.junit5.TestExecutionConfiguration;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;

public class AdviceWithTest extends CamelTestSupport {

    @Override
    public void configureTest(TestExecutionConfiguration testConfiguration) {
        super.configureTest(testConfiguration);
        testConfiguration.withUseAdviceWith(true);
    }

    @Override
    public void configureContext(CamelContextConfiguration contextConfiguration) {
        super.configureContext(contextConfiguration);
        contextConfiguration.withStubEndpoints("jms*");
    }

    @Override
    protected RoutesBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from("kafka:orders?brokers=prod-broker:9092").routeId("orders")
                    .to("http://pricing.internal/price").id("pricing")
                    .setBody(simple("${body} priced"))
                    .to("jms:queue:invoices");
            }
        };
    }

    @Test
    void pricesAndForwardsOrders() throws Exception {
        AdviceWith.adviceWith(context, "orders", route -> {
            route.replaceFromWith("direct:start");
            route.weaveById("pricing").replace().setBody(route.simple("${body} at 9.99"));
            route.mockEndpointsAndSkip("jms:*");
        });
        context.start();

        MockEndpoint invoices = getMockEndpoint("mock:jms:queue:invoices");
        invoices.expectedBodiesReceived("book at 9.99 priced");
        template.sendBody("direct:start", "book");
        MockEndpoint.assertIsSatisfied(context);
        System.out.println("  endpoints after advice: " + context.getEndpoints().stream()
            .map(e -> e.getEndpointUri()).sorted().toList());
    }

    public static void main(String[] args) {
        TestExecutionListener printer = new TestExecutionListener() {
            @Override
            public void executionFinished(TestIdentifier id, TestExecutionResult result) {
                if (id.isTest()) {
                    System.out.println(result.getStatus() + "  " + id.getDisplayName()
                        + result.getThrowable().map(t -> "\n    " + t).orElse(""));
                }
            }
        };
        LauncherFactory.create().execute(LauncherDiscoveryRequestBuilder.request()
            .selectors(DiscoverySelectors.selectClass(AdviceWithTest.class)).build(), printer);
    }
}
Output
endpoints after advice: [direct://start, jms://queue:invoices, mock://jms:queue:invoices]
SUCCESSFUL  pricesAndForwardsOrders()
  • replaceFromWith("direct:start") replaced the Kafka consumer, so the test sends messages directly.
  • weaveById("pricing").replace() swapped the HTTP call for a step that sets a fixed price. Giving steps ids with .id(...) in the route makes them easy to target; weaveByToUri and weaveByType work without ids.
  • mockEndpointsAndSkip("jms:*") sent the message to mock:jms:queue:invoices instead of the queue, and the test checked the final body there: book at 9.99 priced.
  • withStubEndpoints("jms*") let the route start although camel-jms is missing: the jms://queue:invoices endpoint in the list is a stub, an in-memory placeholder. Without it, the route failed to start with No endpoint could be found for: jms://queue:invoices.

Advice must be applied before the context starts, so the test enables it with withUseAdviceWith(true) in configureTest and calls context.start() itself. In Camel 4.23, overriding isUseAdviceWith(), the older way, still works but is deprecated.

Asynchronous routes and the timing traps

When the route runs on another thread, the test can check its mocks before the messages arrive. The alert route here takes 300 ms, and the tests send with asyncSendBody, which returns at once. Three tests check for missing or extra messages, and a fourth waits for a seda route that has no mock:

Java
import java.util.concurrent.TimeUnit;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class AsyncRouteTest extends CamelTestSupport {

    @Override
    protected RoutesBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from("direct:audit")
                    .delay(300)
                    .to("mock:alerts");
                from("seda:import?concurrentConsumers=3")
                    .delay(100)
                    .transform(simple("imported ${body}"));
            }
        };
    }

    @Test
    @Order(1)
    void noAlertExpectedButOneArrivesLater() throws Exception {
        MockEndpoint alerts = getMockEndpoint("mock:alerts");
        alerts.expectedMessageCount(0);
        template.asyncSendBody("direct:audit", "suspicious login");
        long start = System.nanoTime();
        alerts.assertIsSatisfied();
        System.out.println("  count(0) assertion passed after "
            + ((System.nanoTime() - start) / 1000000 < 100 ? "under 100 ms" : "a wait"));
        Thread.sleep(500);
        System.out.println("  alerts received half a second later: "
            + alerts.getReceivedCounter());
    }

    @Test
    @Order(2)
    void sleepForEmptyTestCatchesTheLateAlert() throws Exception {
        MockEndpoint alerts = getMockEndpoint("mock:alerts");
        alerts.expectedMessageCount(0);
        alerts.setSleepForEmptyTest(1000);
        template.asyncSendBody("direct:audit", "suspicious login");
        alerts.assertIsSatisfied();
    }

    @Test
    @Order(3)
    void assertPeriodCatchesTheExtraMessage() throws Exception {
        MockEndpoint alerts = getMockEndpoint("mock:alerts");
        alerts.expectedMessageCount(1);
        alerts.setAssertPeriod(1000);
        template.asyncSendBody("direct:audit", "first");
        template.asyncSendBody("direct:audit", "second");
        alerts.assertIsSatisfied();
    }

    @Test
    @Order(4)
    void waitsForRoutesWithoutMocks() {
        NotifyBuilder notify = new NotifyBuilder(context).from("seda:import*").whenDone(5)
            .create();
        for (int i = 1; i <= 5; i++) {
            template.sendBody("seda:import", "row" + i);
        }
        boolean done = notify.matches(5, TimeUnit.SECONDS);
        System.out.println("  NotifyBuilder saw 5 exchanges done: " + done);
    }

    public static void main(String[] args) {
        TestExecutionListener printer = new TestExecutionListener() {
            @Override
            public void executionFinished(TestIdentifier id, TestExecutionResult result) {
                if (id.isTest()) {
                    System.out.println(result.getStatus() + "  " + id.getDisplayName()
                        + result.getThrowable().map(t -> "\n    " + t.getMessage()).orElse(""));
                }
            }
        };
        LauncherFactory.create().execute(LauncherDiscoveryRequestBuilder.request()
            .selectors(DiscoverySelectors.selectClass(AsyncRouteTest.class)).build(), printer);
    }
}
Output
count(0) assertion passed after under 100 ms
  alerts received half a second later: 1
SUCCESSFUL  noAlertExpectedButOneArrivesLater()
WARN  [main] MockEndpoint - Received exchange: Exchange[<id>]
WARN  [main] MockEndpoint - Received exchange message: Message
WARN  [main] MockEndpoint - Received exchange message body: suspicious login
WARN  [main] MockEndpoint - Received exchange message body type: class java.lang.String
FAILED  sleepForEmptyTestCatchesTheLateAlert()
    mock://alerts Received message count. Expected: <0> but was: <1>
WARN  [main] MockEndpoint - Received exchange: Exchange[<id>]
WARN  [main] MockEndpoint - Received exchange message: Message
WARN  [main] MockEndpoint - Received exchange message body: second
WARN  [main] MockEndpoint - Received exchange message body type: class java.lang.String
WARN  [main] MockEndpoint - Received exchange: Exchange[<id>]
WARN  [main] MockEndpoint - Received exchange message: Message
WARN  [main] MockEndpoint - Received exchange message body: first
WARN  [main] MockEndpoint - Received exchange message body type: class java.lang.String
FAILED  assertPeriodCatchesTheExtraMessage()
    mock://alerts Received message count. Expected: <1> but was: <2>
  NotifyBuilder saw 5 exchanges done: true
SUCCESSFUL  waitsForRoutesWithoutMocks()
  • The first test expected no alert, and passed in under 100 ms, although half a second later the mock had received 1 alert. With a count of 0, there is nothing to wait for, so assertIsSatisfied() returns at once. This test can never fail, which is the worst kind of test.
  • The second test is the same check with setSleepForEmptyTest(1000). The mock waited a second before checking, saw the late alert, and failed with Expected: <0> but was: <1>, as it should.
  • The third test expected exactly one message and got two. Without setAssertPeriod(1000), the assertion would have passed as soon as the first arrived, since "at least 1" was met; the assert period checks again after a second and catches the extra message.
  • The last test used NotifyBuilder to wait until five exchanges from seda:import* were done. The wildcard matters: the consumer's URI is seda://import?concurrentConsumers=3, and seda:import without it did not match, so the builder timed out.

Both failing tests are what the page wants to show: they are the correct versions of the first test. Treat every "no message" and "exactly N" assertion on an asynchronous route with suspicion, and give it a sleep or an assert period longer than the route takes.

Testing routes in a Spring Boot application

When routes are Spring beans, the test should start them the way the application does, with its configuration. camel-test-spring-junit5 adds @CamelSpringBootTest on top of Spring Boot's @SpringBootTest. This test starts a small application on Spring Boot 4.1 with one route, mocks its seda output with an annotation, and injects the mock and a template:

Java
package demo.cameltest;

import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.apache.camel.test.spring.junit5.MockEndpointsAndSkip;
import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.engine.discovery.DiscoverySelectors;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;

@SpringBootApplication
class ShippingApp {
}

@Component
class ShippingRoutes extends RouteBuilder {
    @Override
    public void configure() {
        from("direct:ship").routeId("ship")
            .process(e -> e.getMessage().setHeader("carrier",
                e.getMessage().getBody(String.class).length() > 5 ? "freight" : "post"))
            .to("seda:shipping");
    }
}

@CamelSpringBootTest
@SpringBootTest(classes = ShippingApp.class, properties = {
    "spring.main.banner-mode=off", "logging.level.root=WARN", "camel.main.name=boot-test"})
@MockEndpointsAndSkip("seda:shipping")
public class BootRouteTest {

    @Autowired
    ProducerTemplate template;

    @EndpointInject("mock:seda:shipping")
    MockEndpoint shipping;

    @Test
    void picksCarrierBySize() throws Exception {
        shipping.expectedHeaderValuesReceivedInAnyOrder("carrier", "post", "freight");
        template.sendBody("direct:ship", "book");
        template.sendBody("direct:ship", "wardrobe");
        shipping.assertIsSatisfied();
        System.out.println("  context name: " + template.getCamelContext().getName());
    }

    public static void main(String[] args) {
        TestExecutionListener printer = new TestExecutionListener() {
            @Override
            public void executionFinished(TestIdentifier id, TestExecutionResult result) {
                if (id.isTest()) {
                    System.out.println(result.getStatus() + "  " + id.getDisplayName()
                        + result.getThrowable().map(t -> "\n    " + t).orElse(""));
                }
            }
        };
        LauncherFactory.create().execute(LauncherDiscoveryRequestBuilder.request()
            .selectors(DiscoverySelectors.selectClass(BootRouteTest.class)).build(), printer);
    }
}
Output
context name: boot-test
SUCCESSFUL  picksCarrierBySize()
  • The route found by component scanning sent book with carrier post and wardrobe with carrier freight, and expectedHeaderValuesReceivedInAnyOrder checked both.
  • @MockEndpointsAndSkip("seda:shipping") did the same as mockEndpointsAndSkip in AdviceWith, and @EndpointInject("mock:seda:shipping") injected the resulting mock.
  • The context name was boot-test, taken from the camel.main.name property in the test, which shows that Camel's Spring Boot configuration applied.

The application and route classes are top-level classes in the test file, not nested in the test class. Spring Boot's test support leaves classes nested in a test class out of component scanning, and with the route nested there, the context started without it and the test failed. The program runs with Mockito as a Java agent (-javaagent), as Mockito recommends on JDK 21 and later, because spring-boot-starter-test brings Mockito and it otherwise prints a warning about attaching itself.

What to test in a route

  • Every branch: send one message per when and the otherwise, and check where each one went. That is how missing end() calls, shown on the routing page, are caught.
  • Error paths: use weaveById(...).replace().throwException(...) to make a step fail, then check the dead letter mock, the redelivery count or the error reply.
  • Headers and properties: downstream systems often depend on headers more than on bodies, so assert them.
  • Aggregation and splitting: check the number of messages that come out, not only their content, with an assert period for "exactly N".
  • Configuration: run at least one test through Spring Boot or Camel Main, so that property placeholders and component settings are covered too.

Choosing a testing approach

Test tools for common needs
NeedUse
Check what a route sendsmock: endpoints with expectations set before sending
Fast tests without SpringCamelTestSupport from camel-test-junit5
Replace real consumers and producersAdviceWith: replaceFromWith, weaveById, mockEndpointsAndSkip
Start without a component's jarwithStubEndpoints(...)
Assert that nothing arrivesexpectedMessageCount(0) with setSleepForEmptyTest
Assert exactly N messagesexpectedMessageCount(n) with setAssertPeriod
Wait for routes without mocksNotifyBuilder
Routes and configuration of a Boot application@CamelSpringBootTest with @SpringBootTest

Most tests on this page use the patterns from the other Camel pages: the aggregator page collects its output with mocks, and the error handling page shows the failures worth forcing in tests. For Spring Boot testing in general, outside Camel, see the Spring Boot testing page.