I have a camel route that sends to loadbalancer and processes the response. Is it possible to mock that response somehow in unit test? I tried to use velocity but it doesn't seem to work in unit tests.
Asked
Active
Viewed 3,074 times
1 Answers
-1
Apache already takes care of such testing requirements. There is adviceWith construct which will solve this problem.
Quoting the example directly with few modifications from the link mentioned above:
@Test
public void testAdvised() throws Exception {
context.addRoutes(new RouteBuilder() {
@Override public void configure() throws Exception {
from("direct:start").id("my-route").to("mock:foo");
}
});
context.getRouteDefinition("my-route").adviceWith(context, new RouteBuilder() {
@Override
public void configure() throws Exception {
// intercept sending to mock:foo and do something else
interceptSendToEndpoint("mock:foo")
.skipSendToOriginalEndpoint()
.to("log:foo")
.to("mock:result");
}
});
getMockEndpoint("mock:foo").expectedMessageCount(0);
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
Now here a route is defined as:
from("direct:start").id("my-route").to("mock:foo");
And let's say we want to mock the to
part here.
This is precisely doing it for me:
context.getRouteDefinition("my-route").adviceWith(context, new RouteBuilder() {
@Override
public void configure() throws Exception {
// intercept sending to mock:foo and do something else
interceptSendToEndpoint("mock:foo")
.skipSendToOriginalEndpoint()
.to("log:foo")
.to("mock:result");
}
});
We get the reference of the route definition we want to modify from CamelContext and using the adviceWith method we can define what all action needs to be done. As here, I advised not to send to actual destination i.e. mock:foo
, rather send to two other routes log:foo
and mock:result
.
Hope it answers your query.

Himanshu Bhardwaj
- 4,038
- 3
- 17
- 36
-
1This replaces original endpoint with a mocked one. What I need is to simulate response from the original endpoint. Like in java's Mockito when().then... In my original route that response goes through a list of xstls. – J.Doe Oct 24 '18 at 07:59
-
Even Mockito proxies the class, and does not really execute the method, isn't your intention the same. You want to bypass the rest api call and mock the response? – Himanshu Bhardwaj Oct 24 '18 at 08:04
-
Yes, I'd like to mock the response so it could be processed further – J.Doe Oct 24 '18 at 08:10
-
In that case, you can share your existing route definition and I can look at how we can use this. – Himanshu Bhardwaj Oct 25 '18 at 05:36