Gert Vanthienen's blog

Thursday, June 5, 2008

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 ...

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: ,

2 Comments:

  • Very interesting tip, it really should be added to the smx camel component wiki documentation.

    By Blogger magomarcelo, At August 25, 2008 at 11:59 AM  

  • very interesting..... is such a kind of unit testing added to any example like the loan broker one?

    also is it possible to include unit testing if i havent included separate JBI endpoint jus like in this example?

    By Blogger oops, At October 28, 2009 at 6:40 AM  

Post a Comment

Subscribe to Post Comments [Atom]



<< Home