Issue
I need to execute some initialization / deinitialization code before/after all tests (in all classes) using DI container when SpringExtension
is used. I tried two solutions:
@ExtendWith({BeforeAllAfterAll.class, SpringExtension.class})
@ContextConfiguration(classes = ContextConfig.class)
public class ServiceIT{..}
public class BeforeAllAfterAll implements BeforeAllCallback,
ExtensionContext.Store.CloseableResource {...}
However, in BeforeAllAfterAll
class I can't get reference to application context.
I tried to use events:
public class ContextEventHandler {
@EventListener
public void handleContextStartedEvent(ContextStartedEvent event) {
System.out.println("Context Start Event received.");
}
@EventListener
public void handleContextRefreshEvent(ContextRefreshedEvent event) {
System.out.println("Context Refreshed Event received.");
}
@EventListener
public void handleContextStoppedEvent(ContextStoppedEvent event) {
System.out.println("Context Stopped Event received.");
}
}
However, as I found out when SpringExtension
is used StartedEvent
and StoppedEvent
are not fired.
Could anyone say how to do it? I use Spring5 and JUnit5.
Solution
After studying spring-test source code I did the following solution:
public class BeforeAllAfterAll implements BeforeAllCallback, ExtensionContext.Store.CloseableResource {
private static boolean started = false;
private TestEnvironment testEnvironment;
@Override
public void beforeAll(ExtensionContext context) {
if (!started) {
started = true;
// Your "before all tests" startup logic goes here
Namespace springNamespace = Namespace.create(SpringExtension.class);
Store store = context.getRoot().getStore(springNamespace);
//we need to pass any test class
TestContextManager testContextManager =
store.getOrComputeIfAbsent(FooTest.class, TestContextManager::new, TestContextManager.class);
ApplicationContext applicationContext = testContextManager.getTestContext().getApplicationContext();
testEnvironment = applicationContext.getBean(TestEnvironment.class);
testEnvironment.initialize();
// The following line registers a callback hook when the root test context is shut down
context.getRoot().getStore(GLOBAL).put("any unique name", this);
}
}
@Override
public void close() {
testEnvironment.deinitialize();
}
}
Maybe someone can suggest something better.
Answered By - Pavel_K