如何在使用SpringExtension进行所有测试之前/之后使用上下文执行一些代码



当使用SpringExtension时,我需要在所有测试之前/之后(在所有类中(使用DI容器执行一些初始化/去初始化代码。我尝试了两种解决方案:

@ExtendWith({BeforeAllAfterAll.class, SpringExtension.class})
@ContextConfiguration(classes = ContextConfig.class)
public class ServiceIT{..}
public class BeforeAllAfterAll implements BeforeAllCallback,
ExtensionContext.Store.CloseableResource {...}

然而,在BeforeAllAfterAll类中,我无法获得对应用程序上下文的引用。

我尝试使用事件:

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.");
}
}

然而,正如我所发现的,当使用SpringExtension时,StartedEventStoppedEvent不会被激发。

有人能说怎么做吗?我使用Spring5和JUnit5。

在研究了spring测试源代码后,我完成了以下解决方案:

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();
}
}

也许有人可以提出更好的建议。

相关内容

最新更新