Unit testing Camel routes for ServiceMix
ServiceMix allows you to write integration tests using the Spring framework. In addition to this, there is a little technique that allows you to write unit tests for the Camel routes you'll use inside ServiceMix as well. Write the core routing logic (in this example: a content based router) in an abstract RouteBuilder class ...
... and add the JBI endpoint bindings in a separate class, extending the abstract base routing rules.
This will allow you to write your unit tests using Camel mock endpoints by extending the same abstract base class. In the example below, we put one sample XML document for every supplier in a test resources folder and we have a file: endpoint to send both of them through our RouteBuilder for testing.
public abstract class AbstractRouteBuilder extends RouteBuilder {
protected static final String DIRECT_ROUTER = "direct:router";
protected static final String DIRECT_SUPPLIER1 = "direct:supplier1";
protected static final String DIRECT_SUPPLIER2 = "direct:supplier2";
public void configure() {
from(DIRECT_ROUTER)
.choice()
.when(xpath("/po/supplier/@id = '3125'"))
.to(DIRECT_SUPPLIER1)
.otherwise()
.to(DIRECT_SUPPLIER2);
}
}
... and add the JBI endpoint bindings in a separate class, extending the abstract base routing rules.
public class JbiRouteBuilder extends AbstractRouteBuilder {
@Override
public void configure() {
super.configure();
//adding the JBI bindings
from(DIRECT_SUPPLIER1).to("jbi:service:urn:be:anova:po:supplier1");
from(DIRECT_SUPPLIER2).to("jbi:service:urn:be:anova:po:supplier2");
from("jbi:service:urn:be:anova:po:router).to(DIRECT_ROUTER);
}
}
This will allow you to write your unit tests using Camel mock endpoints by extending the same abstract base class. In the example below, we put one sample XML document for every supplier in a test resources folder and we have a file: endpoint to send both of them through our RouteBuilder for testing.
public class RouteBuilderTest extends ContextTestSupport {
public void testContentBasedRouter() throws Exception {
getMockEndpoint("mock:supplier1").expectedMessageCount(1);
getMockEndpoint("mock:supplier2").expectedMessageCount(1);
assertMockEndpointsSatisifed();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new AbstractRouteBuilder() {
@Override
public void configure() {
super.configure();
from(AbstractRouteBuilder.DIRECT_SUPPLIER1).to("mock:supplier1");
from(AbstractRouteBuilder.DIRECT_SUPPLIER2).to("mock:supplier2");
from("file:src/test/resources/be/anova/smx/purchase?noop=true")
.to(DIRECT_ROUTER);
}
};
}
}
Labels: Camel, ServiceMix