Background: I have two extensions. One that creates some required test data before any test starts and another one that saves unique identifiers of all failed tests, so that they can be retried later. I've noticed that if the first extension throws an exception the second one is never executed even though it implements lifecycle exception handlers.
After investigating it a bit more to see if both extensions are registered and whether they are registered incorrect order I concluded that it might not be possible to catch exceptions thrown in one extension using another extension and that extensions can only catch exceptions thrown from the test classes. But is it so? I couldn't find any definite information in the Junit5 user guide.
Below is a small code sample in Kotlin that demonstrates what I mean.
Extensions:
class ExceptionThrowingExtension: BeforeAllCallback, LifecycleMethodExecutionExceptionHandler {
@Throws(Throwable::class)
override fun handleBeforeAllMethodExecutionException(context: ExtensionContext, throwable: Throwable) {
println("[ExceptionThrowingExtension] handleBeforeAllMethodExecutionException")
throw throwable
}
override fun beforeAll(context: ExtensionContext) {
println("[ExceptionThrowingExtension] beforeAll")
throw RuntimeException("test")
}
}
class ExceptionCatchingExtension: LifecycleMethodExecutionExceptionHandler {
@Throws(Throwable::class)
override fun handleBeforeAllMethodExecutionException(context: ExtensionContext, throwable: Throwable) {
println("[ExceptionCatchingExtension] handleBeforeAllMethodExecutionException")
throw throwable
}
}
Test class:
@ExtendWith(ExceptionCatchingExtension::class, ExceptionThrowingExtension::class)
class ExampleTest {
@Test
@Tag("debug")
fun MyTest() {
println("test")
}
}
My hope was that I'd see handleBeforeAllMethodExecutionException
executed in at least one extension, but all got was:
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.me.ExampleTest
[ExceptionThrowingExtension] beforeAll
Am I missing something or it's not possible to catch exceptions thrown from extension either from that very extension or from another one?