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
endpoint records every exchange it receives and checks it against expectations set beforehand, such as a message count, bodies or headers.mock: - 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
anddirect endpoints instead, without editing the route.mock - NotifyBuilder: waits until a given number of exchanges have finished, for routes whose outputs you do not want to mock.
| Module | Main types | Best for |
|---|---|---|
| camel-mock (comes with camel-core) | MockEndpoint | Recording and checking messages, in any kind of test |
| camel-test-junit5 | CamelTestSupportAdviceWith | Fast tests of routes without Spring |
| camel-test-spring-junit5 | @CamelSpringBootTest@MockEndpointsAndSkip | Routes in a Spring Boot application, with its configuration |
| camel-core | NotifyBuilder | Waiting for asynchronous routes to finish |
The examples use Camel 4.23, JUnit 6.0 and Java 21. Each test class has a main<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:
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();
}
}
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
header of each.priority checked them all and passed.assertIsSatisfied() - After
, the second run expected message 1 to havereset() high. The failure names the message index, the predicate and what it evaluated to:priority .normal == high
Expectations must be set before the messages are sent, because the mock counts arrivals against them as they come in. assertIsSatisfied()setResultWaitTimeexpectedHeaderReceivedexpectedBodiesReceivedInAnyOrderexpectedMinimumMessageCountmessage(i).body().contains(...)
A JUnit test with CamelTestSupport
A test class that extends CamelTestSupportcreateRouteBuilder()templategetMockEndpoint(...)
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);
}
}
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
andorder-3 , zero was filtered out, andorder-7 returnedrequestBody directly, which needs no mock at all.order-5 - The failing test expected
but receivedorder-1 . The assertion message says exactly that, and before failing the mock logged the exchange it received, with its body and body type, at WARN.order-2 - 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)@TestInstance(Lifecycle.PER_CLASS)reset()
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:
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);
}
}
endpoints after advice: [direct://start, jms://queue:invoices, mock://jms:queue:invoices]
SUCCESSFUL pricesAndForwardsOrders()
replaced the Kafka consumer, so the test sends messages directly.replaceFromWith("direct:start") swapped the HTTP call for a step that sets a fixed price. Giving steps ids withweaveById("pricing").replace() in the route makes them easy to target;.id(...) andweaveByToUri work without ids.weaveByType sent the message tomockEndpointsAndSkip("jms:*") instead of the queue, and the test checked the final body there:mock:jms:queue:invoices .book at 9.99 priced let the route start although camel-jms is missing: thewithStubEndpoints("jms*") endpoint in the list is a stub, an in-memory placeholder. Without it, the route failed to start withjms://queue:invoices .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)configureTestcontext.start()isUseAdviceWith()
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 asyncSendBodyseda
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);
}
}
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
returns at once. This test can never fail, which is the worst kind of test.assertIsSatisfied() - The second test is the same check with
. The mock waited a second before checking, saw the late alert, and failed withsetSleepForEmptyTest(1000) , as it should.Expected: <0> but was: <1> - The third test expected exactly one message and got two. Without
, 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.setAssertPeriod(1000) - The last test used
to wait until five exchanges fromNotifyBuilder were done. The wildcard matters: the consumer's URI isseda:import* , andseda://import?concurrentConsumers=3 without it did not match, so the builder timed out.seda:import
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@SpringBootTestseda
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);
}
}
context name: boot-test
SUCCESSFUL picksCarrierBySize()
- The route found by component scanning sent
with carrierbook andpost with carrierwardrobe , andfreight checked both.expectedHeaderValuesReceivedInAnyOrder did the same as@MockEndpointsAndSkip("seda:shipping") in AdviceWith, andmockEndpointsAndSkip injected the resulting mock.@EndpointInject("mock:seda:shipping")- The context name was
, taken from theboot-test property in the test, which shows that Camel's Spring Boot configuration applied.camel.main.name
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
What to test in a route
- Every branch: send one message per
and thewhen , and check where each one went. That is how missingotherwise calls, shown on theend()routing page , are caught. - Error paths: use
to make a step fail, then check the dead letter mock, the redelivery count or the error reply.weaveById(...).replace().throwException(...) - 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
| Need | Use |
|---|---|
| Check what a route sends | mock: |
| Fast tests without Spring | CamelTestSupport |
| Replace real consumers and producers | AdviceWithreplaceFromWithweaveByIdmockEndpointsAndSkip |
| Start without a component's jar | withStubEndpoints(...) |
| Assert that nothing arrives | expectedMessageCount(0)setSleepForEmptyTest |
| Assert exactly N messages | expectedMessageCount(n)setAssertPeriod |
| Wait for routes without mocks | NotifyBuilder |
| Routes and configuration of a Boot application | @CamelSpringBootTest@SpringBootTest |
Most tests on this page use the patterns from the other Camel pages: the