我遇到了一个奇怪的JUnit和Selenium问题。 我想写一个屏幕截图接受者,它会在失败的测试中截取屏幕截图。
我将屏幕截图接受者类定义为:
public class SeleniumJUnitScreenshotTaker implements MethodRule
{
private WebDriver driverLocal;
public SeleniumJUnitScreenshotTaker(WebDriver driver)
{
driverLocal = driver;
}
public void takeScreenshot(String fileName)
{
try
{
new File("test-results/scrshots/").mkdirs(); // Make sure directory is there
FileOutputStream out = new FileOutputStream("test-results/scrshots/" + fileName + ".png");
out.write(((TakesScreenshot) driverLocal).getScreenshotAs(OutputType.BYTES));
out.close();
}
catch (Exception e)
{
// No need to crash the tests here
}
}
public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o)
{
return new Statement()
{
@Override
public void evaluate() throws Throwable
{
try
{
statement.evaluate();
}
catch (Throwable t)
{
takeScreenshot(frameworkMethod.getName());
throw t; // rethrow
}
}
};
}
我是一个基础测试类,我按如下方式设置了WebDriver:
public class TestBase
{
protected static WebDriver driver;
@Rule
public SeleniumJUnitScreenshotTaker seleniumJUnitScreenshotTaker = new SeleniumJUnitScreenshotTaker(driver);
.
.
.
@BeforeClass
public static void intialize()
{
.
.
driver = SeleniumWebDriverFactory.getWebDriver(browser.toString());
if ((browser != Browser.Chrome) && (browser != Browser.ChromeCanary))
{
driver.manage().window().maximize();
}
hostUrl = Configuration.getHostUrl(envUnderTest);
// Open Browser and navigate to main page
driver.navigate().to(hostUrl);
}
@Before
protected void setup() throws Exception
{
this.users = getUsers();
}
@After
protected void teardown()
{
this.testCases.cleanupChecks();
}
@AfterClass
public static void terminate()
{
// Shut down WebDriver
if (driver != null)
driver.quit();
SeleniumWebDriverFactory.stopDriverService();
}
}
问题是当我尝试在测试类中运行一系列测试(从TestBase派生)时,第一次失败后的测试会抛出TimeoutException。这是因为我们不会在测试之间关闭当前浏览器,新测试会尝试查找当前浏览器中缺少的内容。 有没有办法在测试之间关闭浏览器但不关闭驱动程序?或者在测试之间重新安排驱动程序?还有一个alt。可以使这项工作的设计?
由于
亚纳