Junit 5,Spring应用程序上下文未在@DirtiesContext

时间:2018-12-06 19:57:31

标签: java spring selenium-webdriver junit junit5

测试方法后,我的应用程序上下文未关闭。
我在春季5.1.0.RELEASE中使用Junit 5.3.1进行Selenium WebDriver测试。

这是我的豆子:

@Configuration
public class WebDriverConfig {

// ... Some Code ...

@Bean(destroyMethod = "quit")
    @Primary
    public DelegatingWebDriver cleanWebDriver(WebDriver driver) throws Exception {
        driver.manage().deleteAllCookies();
        driver.manage().window().maximize();
        return new DelegatingWebDriver(driver);
    }

// ... Some more code ...
}

这是我的课程:

 @ExtendWith({SpringExtension.class})
@ContextConfiguration(classes = { WebDriverConfig.class, LoggerConfig.class, EmailConfig.class})
@TestExecutionListeners(listeners= {ScreenshotTaker.class, DependencyInjectionTestExecutionListener.class, TestListener.class})
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public class BasicScenariosIT {

    @Inject
    private DelegatingWebDriver driver;

    @SuppressWarnings("unused")
    @Inject
    private URI baseUrl;

    @Inject
    private Logger logger;

    private DelegatingExtentTest testCase;

// ... Some tests ...
}

我希望一行:

  

@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)

关闭应用程序上下文并启动该行:

  

@Bean(destroyMethod =“ quit”)

就我而言,调用方法“ quit”关闭浏览器并启动新的浏览器。但是,这似乎没有发生。 非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

好吧,我找到了解决方法。 我实现了弹簧测试监听器,并在监听器中将上下文标记为脏,而不是依靠@DirtiesContext注释。 侦听器如下所示:

@ExtendWith({SpringExtension.class})
@ContextConfiguration(classes = { WebDriverConfig.class, LoggerConfig.class})
@TestExecutionListeners(listeners= {DependencyInjectionTestExecutionListener.class})
public class RunnerExtension extends AbstractTestExecutionListener {


    @Autowired
    protected Logger logger;

    @Autowired
    protected DelegatingWebDriver driver;

    @Override
    public void beforeTestClass(TestContext testContext) throws Exception {
        testContext.getApplicationContext()
                .getAutowireCapableBeanFactory()
                .autowireBean(this);        
    }

    @Override
    public void beforeTestMethod(TestContext testContext) throws Exception {
        // .. some code here ..
    }

    @Override
    public void beforeTestExecution(TestContext testContext) throws Exception {
        // .. some code here .. 
    }

    @Override
    public void afterTestExecution(TestContext testContext) throws Exception {
        // .. some code here ..
    }

    @Override
    public void afterTestMethod(TestContext testContext) throws IOException {

        // .. some code here ..

        testContext.markApplicationContextDirty(HierarchyMode.EXHAUSTIVE);

    }

    @Override
    public void afterTestClass(TestContext testContext) throws IOException {
        // .. some code here ..

    }
}

重要的代码行是:

  

testContext.markApplicationContextDirty(HierarchyMode.EXHAUSTIVE);

它将上下文标记为脏,并在下一个会话中创建一个新的上下文。