虽然您可以根据 Claus Ibsen 的回答使用拦截和建议来交换端点,但我认为让您的路由接受实例要好得多,Endpoint
这样您的测试就不会与您的生产端点 URI 耦合。
例如,假设您有一个RouteBuilder
看起来像
public class MyRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
from("http://someapi/someresource")
.process(exchange -> {
// Do stuff with exchange
})
.to("activemq:somequeue");
}
}
您可以像这样注入端点:
public class MyRoute extends RouteBuilder {
private Endpoint in;
private Endpoint out;
// This is the constructor your production code can call
public MyRoute(CamelContext context) {
this.in = context.getEndpoint("http://someapi/someresource");
this.out = context.getEndpoint("activemq:somequeue");
}
// This is the constructor your test can call, although it would be fine
// to use in production too
public MyRoute(Endpoint in, Endpoint out) {
this.in = in;
this.out = out;
}
@Override
public void configure() throws Exception {
from(this.in)
.process(exchange -> {
// Do stuff with exchange
})
.to(this.out);
}
}
然后可以像这样测试:
public class MyRouteTest {
private Endpoint in;
private MockEndpoint out;
private ProducerTemplate producer;
@Before
public void setup() {
CamelContext context = new DefaultCamelContext();
this.in = context.getEndpoint("direct:in");
this.out = context.getEndpoint("mock:direct:out", MockEndpoint.class);
this.producer = context.createProducerTemplate();
this.producer.setDefaultEndpoint(this.in);
RouteBuilder myRoute = new MyRoute(this.in, this.out);
context.addRoutes(myRoute);
context.start();
}
@Test
public void test() throws Exception {
this.producer.sendBody("Hello, world!");
this.out.expectedMessageCount(1);
this.out.assertIsSatisfied();
}
}
这具有以下优点:
- 您的测试非常简单易懂,甚至不需要扩展
CamelTestSupport
或其他辅助类
- 这
CamelContext
是手动创建的,因此您可以确保仅创建被测路由
- 测试不关心生产路由 URI
- 如果需要,您仍然可以方便地将端点 URI 硬编码到路由类中