【问题标题】:How do you unit test a servlet endpoint in apache camel?如何在 apache camel 中对 servlet 端点进行单元测试?
【发布时间】:2012-05-22 13:56:15
【问题描述】:

我是 Camel 的新手,现在在我的 Tomcat 服务器上运行了一条简单的路由。路线是这样构建的:

Processor generateWebResponse = new MySpecialProcessor();
from("servlet:///url?matchOnUriPrefix=true").process(generateWebResponse);

我尝试了这样一个简单的单元测试:

Exchange lAuthRequest = createExchangeWithBody("[json body!]");
template.send("servlet:///url", lAuthRequest);
assertEquals("baseline body", lAuthRequest.getOut().getBody());

但是得到一个异常,表明我不能创建一个 servlet 端点。这是异常消息:

org.apache.camel.FailedToCreateProducerException: Failed to create Producer for endpoint: Endpoint[servlet:///url]. Reason: java.lang.UnsupportedOperationException: You cannot create producer with servlet endpoint, please consider to use http or http4 endpoint.

这是新的发展,所以除了好的设计之外我没有太多限制。我愿意接受需要更改路线的建议。另外,如果我在上面做的事情不是惯用的,我很乐意通过任何建议的改进来修改这个问题。

【问题讨论】:

  • 你不写纯单元测试,你要写集成测试。

标签: java unit-testing tomcat junit apache-camel


【解决方案1】:

您需要使用http客户端组件向Tomcat发送消息,例如camel--http组件:http://camel.apache.org/http

然后您需要知道 Tomcat 运行 servlet 的端口号,例如

template.send("http://localhost:8080/myapp/myserver", lAuthRequest);

您需要将 camel-http 添加到您的类路径中,例如,如果您使用 maven,则将其添加为依赖项。

【讨论】:

  • 谢谢克劳斯!有没有推荐的方法来分离路由的 servlet 部分,以便我可以对处理器进行单元测试?我应该对处理器进行简单的旧单元测试吗?
  • 我现在意识到我的问题并不清楚。我试图在我的 webapp 中对路由逻辑进行单元测试。我意识到(正如我在下面记录的)我的大部分逻辑并不依赖于容器。因此,克劳斯回答了我问题的另一部分,即如何集成测试已部署的 web 应用程序。他描述的技术非常强大。我希望它得到更多采用。
  • 有没有办法打印骆驼路线可以触发的完整URL?
【解决方案2】:

我通过将路线分成两部分来解决我的问题。现在路由声明如下所示:

from("servlet:///auth?matchOnUriPrefix=true").inOut("direct:auth");
from("direct:auth").process(new AuthorizationProcessor());

测试看起来像这样:

Exchange lAuthRequest = createExchangeWithBody("test body");
template.send("direct:auth", lAuthRequest);
assertEquals("processed body", lAuthRequest.getOut().getBody());

这不是一个完整的测试,但允许我覆盖所有路由,不包括传入的 servlet 部分。我觉得暂时够用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2012-03-21
    • 2010-09-10
    • 2017-03-25
    • 2015-06-17
    • 2022-06-29
    相关资源
    最近更新 更多