简体   繁体   中英

Unit test Apache Camel specific routes by filtering (Model#setRouteFilter)

How to include only certain routes in my unit test. For example, how do I enable only my-translation-route .

public class TestRoute extends RouteBuilder {
    @Override
    public void configure() {
        from("ftp://my-ftp-server:21/messages")
                .routeId("my-inbound-route")
                .to("direct:my-translation-route");

        from("direct:my-translation-route")
                .routeId("my-translation-route")
                .bean(MyBean.class)
                .to("direct:my-outbound-route");

        from ("direct:my-outbound-route")
                .routeId("my-translation-route")
                .to("http://my-http-server:8080/messages");
    }
}

I tried with Model#filterRoutes but this did not work. All routes were loaded.

class TestRouteTest extends CamelTestSupport {
    @Override
    protected RoutesBuilder createRouteBuilder() {
        return new TestRoute();
    }

    @Override
    public boolean isUseAdviceWith() {
        return true;
    }

    @Test
    void testIfItWorks() throws Exception {
        context.setRouteFilterPattern("my-translation-route", null);

        AdviceWith.adviceWith(context, "my-translation-route", a -> {
            a.mockEndpointsAndSkip("direct:my-outbound-route");
        });

        context.start();

        getMockEndpoint("mock:direct:my-outbound-route").expectedBodyReceived().expression(constant("Hahaha! 42"));

        template.sendBodyAndHeaders("direct:my-translation-route", "42", null);

        assertMockEndpointsSatisfied();
    }
}

I got it working with the override of CamelTestSupport#getRouteFilterIncludePattern , eg:

@Override
public String getRouteFilterIncludePattern() {
    return "direct:my-translation-route";
}

But then this is set for all tests in this test class.

Possible (stupid) solution : set a conditional auto startup for your routes, whose value depends on a (Camel or JVM) property that you can set with a particular value during the unit tests:

public class TestRoute extends RouteBuilder {

    @PropertyInject(name="productionMode", defaultValue="true")
    private boolean productionMode;

    @Override
    public void configure() {
        from("ftp://my-ftp-server:21/messages")
               ...
                .autoStartUp(productionMode); // <=here
     }
       
}

There are various ways to override properties during your tests. See https://camel.apache.org/components/3.17.x/properties-component.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM