【问题标题】:How to execute some code using context before/after all tests with SpringExtension?如何在使用 SpringExtension 进行所有测试之前/之后使用上下文执行一些代码?
【发布时间】:2020-09-17 10:55:09
【问题描述】:

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

@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。

【问题讨论】:

    标签: java spring testing junit


    【解决方案1】:

    在研究了 spring-test 源代码后,我做了以下解决方案:

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

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

    【讨论】:

      猜你喜欢
      • 2013-01-24
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 2016-04-15
      相关资源
      最近更新 更多