如何用模拟测试现有的骆驼端点?

How to test existing camel endpoints with mock?

我目前正在使用 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。 还有,logs表示日志被触发了

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]

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

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

如果不对 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();
    }

}