Mock Component

The mock: component provides a powerful declarative testing mechanism which is similar to jMock in that it allows declarative expectations to be created on an endpoint up front. Then the test is ran which typically fires messages to one or more endpoints and finally the expectations can be asserted in a test case to ensure the system worked as expected.

Testing of distributed and asynchronous processing is notoriously difficult. The MockEndpoint provides a great tool for creating great test cases depite using the various diverse Components in Camel.

URI format

mock:someName

Where someName can be any string to uniquely identify the endpoint

Examples

Here's a simple example of MockEndpoint in use. First the endpoint is resolved on the context. Then we set an expectation, then after the test has run we assert our expectations are met.

MockEndpoint resultEndpoint = context.resolveEndpoint("mock:foo", MockEndpoint.class);

resultEndpoint.expectedMessageCount(2);

// send some messages
...

// now lets assert that the mock:foo endpoint received 2 messages
resultEndpoint.assertIsSatisfied();

You typically always call the assertIsSatisfied() method to test that the expectations were met after running a test.

Setting expectations

You can see from the javadoc of MockEndpoint the various helper methods you can use. You can use other methods such as

Method

Description

expectedMessageCount(int)

to define the expected message count on the endpoint

expectedMinimumMessageCount(int)

to define the minimum number of expected messages on the endpoint

expectedBodiesReceived(...)

to define the expected bodies that should be received (in order)

expectsAscending(Expression)

to add an expectation that messages are received in order using the given expression as an ordering Expression

expectsDescending(Expression)

to add an expectation that messages are received in order using the given expression as an ordering Expression

expectsNoDuplicates(Expression)

to add an expectation that no duplicate messages are received; using an Expression to calculate a unique identifier for each message. This could be something like the JMSMessageID if using JMS, or some unique reference number within the message.

Here's another example

resultEndpoint.expectedBodiesReceived("firstMessageBody", "secondMessageBody", "thirdMessageBody");

Or you could add an expectation on the headers or content of a specific message. For example

resultEndpoint.message(0).header("foo").isEqualTo("bar");

There are some examples of the Mock endpoint in use in the camel-corecore processor tests.