如何使用mock测试现有的camel端点?

时间:2017-06-02 09:28:37

标签: spring-boot apache-camel spring-test

我目前正在使用Camel的模拟组件,我想在现有路线上测试它。基本上我想保留应用程序中定义的现有路由,但在测试期间注入一些模拟,以验证或至少查看当前的交换内容。

基于文档和Apache Camel Cookbook。我试过使用@MockEndpoints

这是路线建设者

@Component
public class MockedRouteStub extends RouteBuilder {

    private static final Logger LOGGER = LoggerFactory.getLogger(MockedRouteStub.class);

    @Override
    public void configure() throws Exception {
        from("direct:stub")
            .choice()
                .when().simple("${body} contains 'Camel'")
                    .setHeader("verified").constant(true)
                    .to("direct:foo")
                .otherwise()
                    .to("direct:bar")
                .end();

        from("direct:foo")
            .process(e -> LOGGER.info("foo {}", e.getIn().getBody()));

        from("direct:bar")
            .process(e -> LOGGER.info("bar {}", e.getIn().getBody()));

    }

}

这是我的测试(目前是一个springboot项目):

@RunWith(SpringRunner.class)
@SpringBootTest
@MockEndpoints
public class MockedRouteStubTest {

    @Autowired
    private ProducerTemplate producerTemplate;

    @EndpointInject(uri = "mock:direct:foo")
    private MockEndpoint mockCamel;

    @Test
    public void test() throws InterruptedException {
        String body = "Camel";
        mockCamel.expectedMessageCount(1);

        producerTemplate.sendBody("direct:stub", body);

        mockCamel.assertIsSatisfied();
    }

}

消息计数为0,看起来更像是未触发@MockEndpoints。 此外,日志表明日志已被触发

route.MockedRouteStub    : foo Camel

我尝试的另一种方法是使用建议:

...
        @Autowired
        private CamelContext context;

        @Before
        public void setup() throws Exception {
            context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() {

                @Override
                public void configure() throws Exception {
                    mockEndpoints();
                }
            });
        }

启动日志表明建议已到位:

c.i.InterceptSendToMockEndpointStrategy : Adviced endpoint [direct://stub] with mock endpoint [mock:direct:stub]

但我的测试仍然失败,消息count = 0。

1 个答案:

答案 0 :(得分:2)

发布适用于我的设置的答案。

如果没有对RouteBuilder进行任何更改,测试将看起来像这样:

@RunWith(CamelSpringBootRunner.class)
@SpringBootTest
@MockEndpoints
public class MockedRouteStubTest  {

    @Autowired
    private ProducerTemplate producerTemplate;

    @EndpointInject(uri = "mock:direct:foo")
    private MockEndpoint mockCamel;

    @Test
    public void test() throws InterruptedException {
        String body = "Camel";
        mockCamel.expectedMessageCount(1);

        producerTemplate.sendBody("direct:stub", body);

        mockCamel.assertIsSatisfied();
    }

}