While you can use intercepts and advice to swap out endpoints as per Claus Ibsen's
answer, I think that it is far better to allow your routes to accept Endpoint
instances so that your tests aren't coupled to your production endpoint URIs.
For example, say you have a RouteBuilder
that looks something like
public class MyRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
from("http://someapi/someresource")
.process(exchange -> {
// Do stuff with exchange
})
.to("activemq:somequeue");
}
}
You can make it possible to inject endpoints like so:
public class MyRoute extends RouteBuilder {
private Endpoint in;
private Endpoint out;
// This is the constructor your production code can call
public MyRoute(CamelContext context) {
this.in = context.getEndpoint("http://someapi/someresource");
this.out = context.getEndpoint("activemq:somequeue");
}
// This is the constructor your test can call, although it would be fine
// to use in production too
public MyRoute(Endpoint in, Endpoint out) {
this.in = in;
this.out = out;
}
@Override
public void configure() throws Exception {
from(this.in)
.process(exchange -> {
// Do stuff with exchange
})
.to(this.out);
}
}
Which can then be tested like this:
public class MyRouteTest {
private Endpoint in;
private MockEndpoint out;
private ProducerTemplate producer;
@Before
public void setup() {
CamelContext context = new DefaultCamelContext();
this.in = context.getEndpoint("direct:in");
this.out = context.getEndpoint("mock:direct:out", MockEndpoint.class);
this.producer = context.createProducerTemplate();
this.producer.setDefaultEndpoint(this.in);
RouteBuilder myRoute = new MyRoute(this.in, this.out);
context.addRoutes(myRoute);
context.start();
}
@Test
public void test() throws Exception {
this.producer.sendBody("Hello, world!");
this.out.expectedMessageCount(1);
this.out.assertIsSatisfied();
}
}
This has the following advantages:
- your test is very simple and easy to understand, and doesn't even need to extend
CamelTestSupport
or other helper classes
- the
CamelContext
is created by hand so you can be sure that only the route under test is created
- the test doesn't care about the production route URIs
- you still have the convenience of hard-coding the endpoint URIs into the route class if you want