In this tutorial we will learn how to test a Camel route using the Mock Component. This route is an example of the direct component which provides direct, synchronous invocation of any consumers when a producer sends a message exchange.
Here is our example:
import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class CamelExampleTest extends CamelTestSupport { @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:in").to("stream:out") .convertBodyTo(String.class) // .process(new Processor() { @Override public void process(Exchange exchng) throws Exception { String body = exchng.getIn().getBody(String.class); System.out.println("Body: " + body); } }).to("mock:endpoint"); } }; } @Test public void test() throws InterruptedException { System.out.println("running test"); MockEndpoint resultEndpoint = context.getEndpoint("mock:endpoint", MockEndpoint.class); context.createProducerTemplate().sendBody("direct:in", "Hello world"); resultEndpoint.expectedBodiesReceived("Hello world"); } }
Notice how it derives from the Camel helper class CamelTestSupport. First, the endpoint is resolved on the context. Then we set an expectation, and then, after the test has run, we assert that our expectations have been met.