首页 > 解决方案 > 骆驼 - 有问题的建议

问题描述

我想创建一个 JUNIT 测试,对于执行数据库搜索的路线,指向我的模拟数据库搜索。

两种搜索都定义为端点:

<endpoint id="select-info" uri="sql:{select ...}"/>
<endpoint id="mock-select-info" uri="sql:{select ...}"/>

目前,我可以实现的唯一方法是更改​​使用模拟端点的路线,但这绝对不是理想的。我在代码中看到了其他使用adviceWith 的JUNIT 测试(所以这不是骆驼发布问题,正如我在其他帖子中看到的那样),但我可能理解错了,因为我没有成功使用它。

所以,假设路线如下:

<route id="request-route" ...>

            <from uri="direct:request-handler" /> 

            <to ref="select-info" />
</route>   

我使用以下代码创建了我的 Junit:

@Test
    public void testEntireRouteWithMockSelect() throws Exception {

        context.getRouteDefinition(ORCHESTRATION_ROUTE_ID).adviceWith(context,
                new AdviceWithRouteBuilder() {
                    @Override
                    public void configure() throws Exception {
                        weaveById("select-info").replace().to("mock-select-info");


                    }
                });

        context.setTracing(true);
        context.start();   

        //response validation and asserts       

    }

我对上面代码的理解是,在路由执行期间,它不会使用“select-info”,而是使用“mock-select-info”,但执行失败并显示错误消息:

***java.lang.IllegalArgumentException: There are no outputs which matches: select-info in the route*** 

根据收到的解释,我知道这与使用 ref 而不是 id 有关。

但我不知道如何改变我的路线。我想过尝试(根据评论,这就是我理解我能做到的方式):

<to ref="select-info" id="select-info"/>

但是它会抛出一个 NullPointerException。

我正在使用骆驼 2.15 顺便说一句。

谢谢!

标签: junitapache-camel

解决方案


引用组件会创建组件的新副本。当您声明一个端点时,您是在声明一个模板而不是一个实际的端点组件。请记住,它是一个实际的端点,它需要在一个<from><to>标记中。

例如:

<endpoint id="select-info" uri="sql:{select ...}"/> <!-- The endpoint ID is used to reference the component-->

此组件的 ID 是select-info您在要使用此端点时在参考中使用此。

例如:

<from ref="select-info"> <!--This component does not have an ID. It does not inherit the ID from the endpoint it references -->

当你像这样声明它时:

 <to ref="select-info" id="select-info"/> 

这是不正确的,因为您有一个重复的端点模板 ID,并且您告诉骆驼<to>端点(模板的副本)具有相同的 ID。ID 必须是唯一的。

将代码更改为此

<to id="to-select-info" ref="select-info"/>

请注意,现在将运行的组件副本的 ID 为to-select-info. 这是实际在路由中运行的组件。当您 weaveById 并将select-info其用作值时,它不会找到组件,但会找到组件模板。这就是为什么它是一个 NULL 指针,没有组件调用select-info只有模板调用select-info

将您的测试代码更改为:

public void configure() throws Exception {
                    weaveById("to-select-info").replace().to("mock-select-info");

在上面的示例中,我选择了to-select-info可​​以替换的端点,因为它是实际组件而不是模板。


推荐阅读