WireMockTestExecutionListener#applicationContextBroken triggers load of failure app context for multiple times
Describe the bug version: spring-cloud-contract-wiremock-3.1.3
I'm using spring cloud contract wiremock for integration testing. Sometimes my application context couldn't be created due to the exception thrown during the bean initialization process.
I expected the test to fail immediately after application context failure. but from the test log, I saw that the application context reloaded for multiples times and make it hard to debug. (we have some stateful component which couldn't be initialized twice and last context failure reason may not be the root cause)
in WireMockTestExecutionListener::applicationContextBroken, testContext.getApplicationContext() tries to load the context, and the method is called in beforeTestClass, afterTestClass and afterTestMethod:
private boolean applicationContextBroken(TestContext testContext) {
try {
testContext.getApplicationContext();
return false;
}
catch (Exception ex) {
if (log.isDebugEnabled()) {
log.debug("Application context is broken due to", ex);
}
return true;
}
}
Sample I have a component which throws exception on creation:
@Slf4j
@Profile("failure")
@Component
public class FailureComponent {
private static AtomicInteger counter = new AtomicInteger();
public FailureComponent() {
log.info("start failure component {}", counter.getAndIncrement());
throw new IllegalStateException("fail forever");
}
}
I expected that the component would only be loaded once, and then fail the test. but it runs for multiple times:
2022-10-29 11:53:38.102 INFO 11320 --- [ main] c.h.h.s.k.t.wiremock.FailureComponent : start failure component 0
2022-10-29 11:53:38.477 INFO 11320 --- [ main] c.h.h.s.k.t.wiremock.FailureComponent : start failure component 1
2022-10-29 11:53:38.711 INFO 11320 --- [ main] c.h.h.s.k.t.wiremock.FailureComponent : start failure component 2
2022-10-29 11:53:38.970 INFO 11320 --- [ main] c.h.h.s.k.t.wiremock.FailureComponent : start failure component 3
I'm not sure what the exact intent of that code is; however, it may be possible to benefit from org.springframework.test.context.TestContext.hasApplicationContext() which was introduced in Spring Framework 5.2.
Regarding repeated ApplicationContext failures, that has been addressed for Spring Framework 6.1. See Context Failure Threshold for details.