This is my simple route:
@Override
public void configure() {
onException(Exception.class)
.handled(true)
.process(exchange -> {
Exception exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
log.error(logFormat.error(exchange, exception, exception.getMessage()));
exchange.getIn().setBody(exception.getMessage());
exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, HttpStatus.SC_INTERNAL_SERVER_ERROR);
});
onException(HttpOperationFailedException.class)
.handled(true)
.to("direct:handleHttpOperationFailed");
from("direct:myRoute")
.routeId("myRoute")
.log("Route start: myRoute")
.id("startStep")
.process(
exchange -> log.info("Doing some processing")
)
.id("processingStep")
.end();
}
Now I want to write some tests:
- exception handling case - exception is thrown after "processingStep" and handled in onException
- positive scenario - all flow is passing without exceptions
And this is what I have done...
My test annotations:
@RunWith(CamelSpringBootRunner.class)
@UseAdviceWith
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class StarlingFpsInboundWebhookIT {
...
}
My two test cases:
- With exception scenario - here I use adviceWith to throw exception after "processingStep":
@Test
public void exceptionScenario() throws Exception {
// Given
context.getRouteDefinition("myRoute").adviceWith(context, new AdviceWithRouteBuilder() {
@Override
public void configure() {
weaveById("processingStep").after()
.process(exchange -> {
throw ExceptionFixtures.createSimpleException();
})
.id("exceptionThrowStep");
}
});
context.start();
String requestBody = ResourcesHelper.read(this.getClass(), "/data/input/request.json");
// When
template.send("direct:myRoute", camelExchange -> {...});
}
- Success case - here I need to delete previously created "exceptionThrowStep" to not to throw Exception:
@Test
public void successScenario() throws Exception {
// Given
context.getRouteDefinition("myRoute").adviceWith(context, new AdviceWithRouteBuilder() {
@Override
public void configure() {
weaveById("exceptionThrowStep").remove();
}
});
context.start();
String requestBody = ResourcesHelper.read(this.getClass(), "/data/input/request.json");
// When
template.send("direct:myRoute", camelExchange -> {...});
}
And when I run those tests (first exception then successful scenario) I get exception in second test:
org.apache.camel.FailedToCreateRouteException:
Failed to create route myRoute at:
>>> pipeline -> [[]] <<<
in route: Route(myRoute)[[From[direct:myRoute]...
because of Definition has no children on pipeline -> [[]]
Why this exception occurs? I have read many articles but nothing precious found about this case :( What is interesting - when in second test in adviceWith I use replace() instead of remove() everything is working...
My question are:
- Is is good approach to test exception handling in route?
- Can we reset the route definition between tests to avoid my approach?