【问题标题】:Camel junit test http component with bean componentCamel junit用bean组件测试http组件
【发布时间】:2016-05-18 05:22:23
【问题描述】:

我的骆驼上下文中有这样的路线:-

<camel:route id="xxx">
 <camel:from uri="direct:test"></camel:from>
 <camel:to uri="bean:testProcessor"></camel:to>
 <camel:to  uri="{{testUrl}}"></camel:to>
 <camel:to uri="bean:responseHandler"></camel:to>
</camel:route>

我想测试整个路由。所以每当我向 direct:test 发送请求时,它都会调用 testProcessor,然后使用 testUrl 调用 http 服务,然后调用 responseHandler bean 元素。我该如何测试呢?最重要的是这里存根 http 服务

【问题讨论】:

    标签: java junit spring-boot apache-camel


    【解决方案1】:

    我在理解您的确切用例时遇到了一些麻烦,因此我将向您介绍可用于测试的骆驼的 AdviceWithRouteBuilder 库。我在基于骆驼 xml 的版本中不是 100% 流畅,所以我将使用 Java DSL 作为我的示例。以下是一些可用作参考的骆驼文档的链接: http://camel.apache.org/advicewith.html

    //示例路由

    from("direct:myNormalInput").routeId("xxx")
        .to("myBean", "myMethod").id("enrichmentBean")
        .to("http://myawesomeurl").id("HttpCaller")
        .to("myResponseBean", "myMethod").id("responseHandler");
    

    //样本单元测试

    public void myTest throws Exception {
        context.getRouteDefinition("xxx").adviceWith(context, new AdviceWithRouteBuilder() {
            //You can replace your normal route's from statement
            replaceFromWith("direct:testEntry");
            //Swap out your enrichmentBean with a replace or remove it if you prefer
            weaveById("enrichmentBean").replace().to("myTestBean", "myTestMethod");
            //mock out your http call with a different url or a fake endpoint
            weaveById("HttpCaller").replace().to("http://myTestUrl");
            //extract your message at any point in processing to do some validation work
            weaveById("responseHandler").after().to("mock:extract");
        }
        context.start();
    
        template.sendBody("direct:testEntry", "myTestBody");
    
        MockEndpoint test = getMockEndpoint("mock:extract");
        int messageCount =  test.getReceivedExchanges().size();
        assertEquals(1, messageCount);
    }
    

    【讨论】:

      【解决方案2】:

      您还可以在单​​元测试中动态添加带有 Jetty 消费者的路由。这样,您可以实际测试 Web 服务行为。我在编写集成测试时倾向于这样做,并且非常有用。否则,正如 Matthew 建议的那样,您可以将其模拟出来。

      【讨论】:

      • 您能否提供一个在单元测试中即时使用 Jetty 消费者的示例?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多