如何在不加载 bean 的情况下测试骆驼路线

我编写了一个 Camel Route,其中包含一些引用 bean 的组件。当然,我想对该路由进行单元测试,但是我在编写独立于 bean 的测试时遇到了问题。

确切地说,我正在使用 mongodb 组件来获取集合中的所有文档。该组件需要一个自动注入的 MongoClient bean。

在我的单元测试中,我使用带有存根数据的模拟组件替换了 mongodb 组件,在测试设置中使用了adviceWith()。我还使用 Mockito.mock 注册了组件,但是由于没有要连接的数据库,MongoClient 总是以失败的连接开始。为什么我还认为我可能会吠错树而 Spring 导致了我的问题。

测试工作正常,但测试也开始建立与 mongodb 的连接。我的个人目标不是开始连接。你们中的任何人都可以给我一个提示,我应该尝试什么。

我熟悉的唯一方法是将端点 url 存储在属性文件中并在应用程序中引用键。我希望找到更好的解决方案。

我使用的是 3.8 版的骆驼弹簧靴原型,并增强了现有的路线和测试。

wuchun198799 回答:如何在不加载 bean 的情况下测试骆驼路线

在启动上下文之前,您可以覆盖 startCamelContext 方法并使用 weaveByIdweaveByToUri 替换有问题的端点,AdviceWithRouteBuilder

@Override
protected void startCamelContext() throws Exception {
    
    context.getRouteDefinition("queryDBForTasks").adviceWith(context,new AdviceWithRouteBuilder(){

        @Override
        public void configure() throws Exception {
            weaveByToUri("jdbc:*")
                .replace()
                .to("mock:jdbc");
        }
    });
    
    super.startCamelContext();
}

之后,在测试开始时,您可以使用 AdviceWithRouteBuilder 和 weave 方法来控制这些模拟端点的行为。

@Test
public void TestJDBCRoute() throws Exception {

    context.getRouteDefinition("queryDBForTasks").adviceWith(context,new AdviceWithRouteBuilder(){

        @Override
        public void configure() throws Exception {
            
            weaveByToUri("mock:jdbc")
                .after()
                .setBody(constant(getTasksForTest()));

            weaveAddLast()
                .setProperty("testResultCount").simple("${body.size()}")
                .to("mock:result");
        } 
    });

    MockEndpoint resultMockEndpoint = getMockEndpoint("mock:result");
    resultMockEndpoint.expectedMessageCount(1);
    resultMockEndpoint.message(0)
        .exchangeProperty("testResultCount").isEqualTo(4);

    template.sendBody("direct:queryDBForTasks",null);

    resultMockEndpoint.assertIsSatisfied();
}

对于任何具有消费者端点(如计时器、cron 作业或需要 bean 或连接在测试期间不可用的端点)的有问题的路由,您可以使用 removeRouteDefinition 中的 startCamelContext 删除所述路由。

@Override
protected void startCamelContext() throws Exception {
    
    context.removeRouteDefinition(
        context.getRouteDefinition("someRoute"));        
    super.startCamelContext();
}
本文链接:https://www.f2er.com/1055.html

大家都在问