测试方法后我的应用程序上下文未关闭。
我使用 Junit 5.3.1、spring 5.1.0.RELEASE 进行 Selenium WebDriver 测试。
这是我的 bean :
@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”关闭浏览器并启动一个新浏览器。然而这似乎并没有发生。 非常感谢您的帮助
最佳答案
嗯,我找到了一个解决方法。
我实现了 spring 测试监听器,并在监听器中将上下文标记为脏,而不是依赖 @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);
它将上下文标记为脏,并且将在下一个 session 中创建新的上下文。
关于java - Junit 5,Spring 应用程序上下文未在 @DirtiesContext 上关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53658764/