1

我正在使用 JUnit 和 Selenium 运行端到端测试,被测应用程序经常配置错误,我希望能够在所有测试之前运行一次设置。

如何从 TestExecutionListener 中获取对测试的应用程序上下文的引用?

我使用 @SpringJUnitConfig 扩展来运行我的测试。

import static org.junit.jupiter.api.Assertions.fail;

import org.junit.jupiter.api.Test;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

@SpringJUnitConfig(SpringConfig.class)
public class SampleTest {

    @Test
    void test1() {
        fail();
    }

}

我需要从 TestExecutionListener 内的应用程序上下文访问 bean,以通过覆盖 testPlanExecutionStarted 来进行一些初始设置。

import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestPlan;

public class TestSetupListener implements TestExecutionListener {

    @Override
    public void testPlanExecutionStarted(final TestPlan testPlan) {
        // Get reference to applicationContext
    }

}

我想知道是否有一种方法可以访问我的测试将使用的相同 ApplicationContext 或者框架此时不知道测试应用程序上下文?

我尝试使用 SpringExtension.getApplicationContext,但无法从 TestExecutionListener 中获取对 ExtensionContext 的引用。

4

1 回答 1

0

我能找到的最好的方法是使用以下

/**
 * Registered through META-INF/spring.factories file as a default Listener
 * Ensures that the AUT is in a testable state
 */
public class TestSetupListener extends AbstractTestExecutionListener {
    private boolean setupRequired = true;

    @Autowired
    <What you need autowired>

    @Override
    public void beforeTestClass(final TestContext testContext) throws Exception {
        if (setupRequired) {
            setupRequired = false;
            ApplicationContext applicationContext = testContext.getApplicationContext();
            applicationContext.getAutowireCapableBeanFactory().autowireBean(this);
            ...
        }
    }
于 2019-10-03T18:54:49.630 回答