【问题标题】:Apache Camel MockEndpoint mock the outputApache Camel MockEndpoint 模拟输出
【发布时间】:2016-11-22 16:04:39
【问题描述】:

假设我有这样一条 apache 骆驼路线:

from("direct:start")
    .routeId("aRouteId")
    .bean(someBusinnessTransformationBean).id("transformationBean")
    .bean(aPersistenceBean).id("persistenceBean")
    .to("direct:target");

然后,在我的单元测试中,我正在做类似的事情:

public class RouteTest extends CamelTestSupport {
    @Override
    public boolean isDumpRouteCoverage() { return true }

    @Override
    public boolean isUsedAdviceWith() { return true }

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

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

    @Test
    public void testRoute() throws Exception {
        context.getRouteDefinition("aRouteId").adviceWith(context, new AdviceWithRouteBuilder() {
            @Override
            public void configure() throws Exception {
                weaveById("transformationBean")
                    .replace()
                    .multicast()
                    .to(mockTransformationBean);

                weaveById("persistenceBean")
                    .replace()
                    .multicast()
                    .to(mockPersistenceBean);
            }
        });

        context.start();

        // Asserts the expectedMessageCount

        // Send a message with template.sendBody...

        assertMockEndpointSatisfied();
    }
}

问题:

我怎样才能正确地对该路由进行单元测试,而不仅仅是确保 messageCount 和接收到的正文(在第一个 bean 上)。

例如,我如何像使用 Mockito 进行单元测试一样模拟 MockEndpoint 的响应:

when(mockTransformationBean.someHandler(...)).thenReturn(anExpectedObjectForMyUnitTestPropose);

干杯,尼古拉斯

【问题讨论】:

  • 为什么不直接运行单元测试,然后将交换主体与一些预期主体进行比较?
  • 因为我找不到用apache camel MockEndpoint拦截bean的交换体的方法。我能做的是确保接收到的主体到模拟,但是,我想确保第一个 bean 转换主体并将不同的主体发送到第二个 bean。
  • 你可以在 bean 拦截后做一个 adviceWith 和发送到一个 mockendpoint。然后断言消息应该是什么。

标签: java unit-testing mocking apache-camel


【解决方案1】:

经过一些研究、阅读文档等,我想出了一个可以接受的解决方案:

weaveById("transformationBean")
    .replace()
    .to(mockTransformationBean)
    .setBody(constant(<myExpectedMockResponse>));

所以稍后,我可以做如下断言:

mockPersistenceBean.expectedBodiesReceivedInAnyOrder(
    <myExpectedMockResponse>
);

这样,不仅可以确保 bean 和端点是否接收到正确的正文/标头,还可以确保路由之间的任何转换是否正确完成。

因此可以从单元的角度测试代码的输入和输出,而不是将其与单元测试中不需要的许多其他组件集成。

【讨论】:

    【解决方案2】:

    您可以单独建立交换并调用 bean 方法;也就是说,不要通过 Camel 发送它们 - 只需直接调用 bean。这是一个更可控、更有针对性的单元测试。

    【讨论】:

    • 好的,我明白了。唯一让我感到困惑的是,我如何确保所有编写的骆驼路线都正确编写? bean 本身已经有单元测试。但是我怎么能确保以后对代码进行维护的开发人员不会破坏路由,而不破坏 bean?
    • 那么你为什么不创建一个交换,并在你的单元测试中将交换或交换主体发送到 bean 类,然后进行期望匹配。要测试整个路由,您需要运行路由并模拟掉外部依赖项。
    猜你喜欢
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 2023-03-08
    • 2018-06-12
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多