It is common that many of your integrations will call out to endpoints from which you will expect a reply, such as when invoking a web service. We saw how mock endpoints could be used to assess message content in a test in the Using mock endpoints to verify routing logic recipe. We will now use those same endpoints to define the test responses.
To use this recipe you should first have a route test set up as described in the Testing routes defined in Java recipe.
The Java code for this recipe is located in the org.camelcookbook.examples.testing.mockreply
package.
In the following route, we have a mock endpoint from which we would like a response:
from("direct:in") .inOut("mock:replying") .to("mock:out");
To test this, get a handle to the mock endpoint that you want to simulate a reply from, as described in the Testing routes defined in Java recipe. Before a message is sent into the route, define how you want the endpoint to respond through the
whenAnyExchangeReceived(Processor)
method:
mockReplying.whenAnyExchangeReceived(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
in.setBody("Hey " + in.getBody());
}
});
The Processor
instance that you have provided to the mock endpoint will be called for every exchange that reaches that mock endpoint. This can be thought of as the default reply. On top of this, you can specify that you want a different processor to be engaged for a particular message. In the following example, we specify a different processor to be used for the first message received; all other messages received will use the processor provided in the previous call to whenExchangeReceived
:
mockReplying.whenExchangeReceived(1, new Processor() { @Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); in.setBody("Czesc " + in.getBody()); // Polish } });
Using a processor gives you maximum flexibility with what you can do when manipulating responses. It may be, however, that what you want to do can be described with a Camel Expression. In this case, the following approach might be more straightforward:
mockReplying.returnReplyBody( SimpleBuilder.simple("Hello ${body}"));
You can also set a header as the reply from an endpoint.
mockReplying.returnReplyHeader("someHeader", ConstantLanguage.constant("Hello"));
You cannot use the two returnReply..()
methods on the same endpoint in the same test, as the second one will override the first. If you want to set a header and body, use the processor approach instead.
You may be used to having Expression Languages at your fingertips when writing a RouteBuilder
implementations. Since test classes do not usually extend this base class, you have to use the static methods defined on the individual expression language classes directly. For example:
import static org.apache.camel.language.simple.SimpleLanguage.simple;
18.118.12.50