我正在使用骆驼编写一个应用程序(最终)在保险丝容器中进行部署。该项目的性质要求我混合使用Java和XML DSL。
我无法使模拟框架与蓝图一起正常工作。
这是我的单元测试,完全基于示例here。
public class MockNotWorking extends CamelBlueprintTestSupport {
@Test
public void testAdvisedMockEndpointsWithPattern() throws Exception {
context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() {
@Override
public void configure() throws Exception {
mockEndpoints("log*");
}
});
getMockEndpoint("mock:log:foo").expectedBodiesReceived("Bye World");
getMockEndpoint("mock:result").expectedBodiesReceived("Bye World");
template.sendBody("direct:start", "Hello World");
// additional test to ensure correct endpoints in registry
assertNotNull(context.hasEndpoint("direct:start"));
assertNotNull(context.hasEndpoint("log:foo"));
assertNotNull(context.hasEndpoint("mock:result"));
// only the log:foo endpoint was mocked
assertNotNull(context.hasEndpoint("mock:log:foo"));
assertNull(context.hasEndpoint("mock:direct:start"));
assertNull(context.hasEndpoint("mock:direct:foo"));
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").to("direct:foo").to("log:foo").to("mock:result");
from("direct:foo").transform(constant("Bye World"));
}
};
}
protected String getBlueprintDescriptor() {
return "OSGI-INF/blueprint/blueprint.xml";
}
}
我已经逐字复制了示例here,并对其做了非常小的修改,因此我们扩展了
CamelBlueprintTestSupport
而不是CamelTestSupport
。这需要重写getBlueprintDescriptor
指向我的蓝图xml,在该xml中,我定义了一条非常基本的路线(与测试完全无关):<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<camelContext id="validationRoute" xmlns="http://camel.apache.org/schema/blueprint" >
<route id="validation">
<from uri="direct:validation" />
<log message="validating..." />
</route>
</camelContext>
</blueprint>
测试失败并显示:
java.lang.AssertionError: mock://log:foo Received message count. Expected: <1> but was: <0>
因此,这意味着消息未到达模拟端点。将
CamelBlueprintTestSupport
更改为CamelTestSupport
即可。那么,如何获得类似蓝图的模拟作品呢?
最佳答案
使用蓝图时,它将导入您在蓝图xml文件中定义的所有路由,并将它们添加到CamelContext
。
造成这种情况中断的原因是context.getRouteDefinitions().get(0)
不再引用唯一的路由-现在有不止一条。因此,当您添加AdviceWithRouteBuilder
时,可能会将其添加到错误的路由。
以下代码解决了该问题(也适用于非蓝图测试):
List<RouteDefinition> routes = context.getRouteDefinitions();
for (int i=0; i<routes.size(); i++) {
context.getRouteDefinitions().get(i).adviceWith(context, new AdviceWithRouteBuilder() {
@Override
public void configure() throws Exception {
// mock all endpoints
mockEndpoints("log*");
}
});
}
======更新======
更好的方法是模拟所有路线,而不是通过ID查找我们的特定路线,然后应用建议。这意味着首先设置路线ID:
from("direct:start").routeId("start").to("direct:foo").to("log:foo").to("mock:result");
然后像以前一样通过id查找路由并调用
adviceWith
:context.getRouteDefinition("start").adviceWith(context, new AdviceWithRouteBuilder() {
@Override
public void configure() throws Exception {
// mock log endpoints
mockEndpoints("log*");
}
});