6單元測試雖然你可以使用攔截和建議換出端點按克勞斯易卜生的 答案,我認爲這是更好的,讓你的路由接受Endpoint
實例,以使您的測試AREN」 t耦合到您的生產端點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到路徑類,如果你想