E. Nikolas de Oliveira E. Nikolas de Oliveira - 15 days ago 8
Java Question

Apache Camel MockEndpoint mock the output

Let's say I have an apache camel route like this:

from("direct:start")
.routeId("aRouteId")
.bean(someBusinnessTransformationBean).id("transformationBean")
.bean(aPersistenceBean).id("persistenceBean")
.to("direct:target");


And then, on my unit tests, I'm doing something like:

public class RouteTest extends CamelTestSupport {
@Override
public boolean isDumpRouteCoverage() { return true }

@Override
public boolean isUsedAdviceWith() { return true }

@EndpointInject(uri = "mock:mockTransformationBean")
protected MockEndpoint mockTransformationBean;

@EndpointInject(uri = "mock:mockPersistenceBean")
protected MockEndpoint mockPersistenceBean;

@Test
public void testRoute() throws Exception {
context.getRouteDefinition("aRouteId").adviceWith(context, new AdviceWithRouteBuilder() {
@Override
public void configure() throws Exception {
weaveById("transformationBean")
.replace()
.multicast()
.to(mockTransformationBean);

weaveById("persistenceBean")
.replace()
.multicast()
.to(mockPersistenceBean);
}
});

context.start();

// Asserts the expectedMessageCount

// Send a message with template.sendBody...

assertMockEndpointSatisfied();
}
}


Question:

How could I unit test this route properly, instead of just ensure the messageCount and received body (on the first bean).

Like, how could I mock the response of a MockEndpoint as I could do when using Mockito for unit testing:

when(mockTransformationBean.someHandler(...)).thenReturn(anExpectedObjectForMyUnitTestPropose);


Cheers, Nikolas

Answer

After some research, documentation reading and so on, I come up with an acceptable solution for this:

weaveById("transformationBean")
    .replace()
    .to(mockTransformationBean)
    .setBody(constant(<myExpectedMockResponse>));

So later on, I can just do an assert like:

mockPersistenceBean.expectedBodiesReceivedInAnyOrder(
    <myExpectedMockResponse>
);

This way, it is possible to ensure not just if the beans and endpoints are receiving the proper body / header, but if any transformation in between the route is being done properly as well.

So it is possible to test the input and output of the code from a unit point of view, instead integrating it with a lot of other components unnecessary in an unit test.