如何在Apache Camel中测试多个RouteBuilder

时间:2014-01-22 22:25:44

标签: java unit-testing apache-camel

我想在单个单元测试中测试多个camel RouteBuilder 我有什么:

改变状态的自定义camel处理器

public class MyProcessor implements Processor {
   MyState state;
   public MyProcessor(MyState state) {this.state = state;}

   @Override
   public void process(Exchange exchange) throws Exception {
   state.setState(state.getState() + 5);
   }}

两个简单的RouteBuilder:首先将消息从“direct:start”路由到“direct:endroute1”,然后从“direct:endroute1”路由第二个拾取消息并路由到某处“mock:endroute2”

public class MyRouteBuilder1 extends RouteBuilder {
    MyState state;
    public MyRouteBuilder1(MyState state) {this.state = state;}

    @Override
    public void configure() throws Exception {
        from("direct:start").process(new MyProcessor(state)).to("direct:endroute1");
    }}

public class MyRouteBuilder2 extends RouteBuilder {
    MyState state;
    public MyRouteBuilder2(MyState state) {this.state = state;}

    @Override
    public void configure() throws Exception {
        from("direct:endroute1").process(new MyProcessor(state)).to("mock:endroute2");
    }}

为单个路径构建器编写单元测试非常简单:

public class MyTest extends CamelTestSupport {
    MyState state = new MyStateImpl();

    @EndpointInject(uri = "mock:result")
    protected MockEndpoint resultEndpoint;

    @Test
    public void testSingleRoute() throws Exception {
        resultEndpoint.expectedMessageCount(1);
        template.sendBody("direct:start", new Object());
        assertTrue(state.getState() == 5);
        resultEndpoint.assertIsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
     return new MyRouteBuilder1(state) {
            public void configure() throws Exception{
               super.configure();
               from("direct:endroute1").to("mock:result");
           }
     };
 }
}

我真正想做的是以某种方式覆盖CamelTestSupport.createRouteBuilder,它将测试从direct:startmock:endroute2的整个消息处理链。因此state.getState()应为10

3 个答案:

答案 0 :(得分:2)

您可以使用context.addRoutes(RouteBuilder) API

将多个RouteBuilder添加到上下文中

请参阅此单元测试以获取示例:

https://svn.apache.org/repos/asf/camel/trunk/camel-core/src/test/java/org/apache/camel/builder/AddRoutesAtRuntimeTest.java

答案 1 :(得分:0)

您可以使用一个RouteBuilder including多个其他RouteBuilders的路由。

答案 2 :(得分:0)

尝试覆盖方法:

protected RouteBuilder[] createRouteBuilders() {...}

来自CamelTestSupport。从2.17版开始可用