I don't know how to test an endpoint rest with Apache Camel 3. Can you help me?
That's my code. unmarshal a xml to pojo, then pojo to json and send it to an external service "my.applications.url". I need to mock the external response. How can i do it?
from("direct:my-application")
.id("my-application")
.log("app: ${body}")
.log("country: ${headers.country}")
.unmarshal(jaxbDataFormat).process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
ApplicationInput bodyIn = (ApplicationInput) exchange
.getIn().getBody();
exchange.getIn().setBody(bodyIn);
}
}).setHeader(Exchange.HTTP_METHOD).constant(HttpMethod.POST).marshal().json(JsonLibrary.Jackson)
.toD("{{my.applications.url}}?throwExceptionOnFailure=false") //<--- I need to mock in in test
.choice()
.when((header("CamelHttpResponseCode").isEqualTo("200")))
.unmarshal().json(JsonLibrary.Jackson, NCCLResponse.class)
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
int responseCode = in.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
myResponse response = (myResponse) exchange.getIn().getBody();
//create response
myApplicationOutput output = createResponseOk(responseCode, response);
exchange.getIn().setBody(output);
}
})
.otherwise()
.unmarshal().json(JsonLibrary.Jackson, myResponse.class)
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
int responseCode = in.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
myResponse response = (myResponse) exchange.getIn().getBody();
//create response
ErrorResponse output = createResponseError(responseCode, response);
exchange.getIn().setBody(output);
}
})
.end();```
If you want to mock this call in a Camel route test, you can use AdviceWith.
1) Add an identifier/marker to the route step you want to mock
.toD("{{my.applications.url}}?throwExceptionOnFailure=false").id("RequestToMock")
2) Then use AdviceWith to replace the marked step with something else
context.getRouteDefinition("yourRouteId").adviceWith(context, new AdviceWithRouteBuilder() {
@Override
public void configure() throws Exception {
weaveById("RequestToMock") // <-- same identifier
.replace()
.setBody(simple("resource:classpath:TestResponse.json"));
}
});
3) Tell Camel that your test uses AdviceWith (depending what type of test you have)
@UseAdviceWith // for Spring Boot tests
@Override
public boolean isUseAdviceWith() { // for CamelTestSupport
return true;
}