【发布时间】:2013-11-12 03:11:55
【问题描述】:
我在 Webdriver 中使用 Java,但在测试失败时截屏时遇到问题。
我的 jUnit 测试:
....
public class TestGoogleHomePage extends Browser {
....
@Test
public void testLoadGoogle() {
//this test will fail
}
}
我的浏览器类:
public class Browser {
protected static WebDriver driver;
public Browser() {
driver = new FirefoxDriver();
}
.....
@Rule
public TestWatcher watchman = new TestWatcher() {
@Override
protected void failed(Throwable e, Description description) {
File scrFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File(
"C:\\screenshot.png"));
} catch (IOException e1) {
System.out.println("Fail to take screen shot");
}
// this won't work
// driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@Override
protected void succeeded(Description description) {
....
}
};
@After
public void closeBrowser() {
driver.quit();
}
}
执行测试会产生如下错误信息(部分错误信息):
org.openqa.selenium.remote.SessionNotFoundException: 调用 quit() 后无法使用 FirefoxDriver。
看起来它在抱怨我的 @After 方法。
我尝试将浏览器类更改为:
public class Browser {
protected static WebDriver driver;
public Browser() {
driver = new FirefoxDriver();
}
.....
@Rule
public TestWatcher watchman = new TestWatcher() {
@Override
protected void failed(Throwable e, Description description) {
File scrFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File(
"C:\\screenshot.png"));
} catch (IOException e1) {
System.out.println("Fail to take screen shot");
}
driver.quit();
}
@Override
protected void succeeded(Description description) {
....
driver.quit();
}
};
}
上面的代码工作正常。但我不想在那里退出驱动程序,因为每次测试运行后我可能还想清理其他东西,并且我想在 @After 方法中关闭浏览器。
有什么办法可以做到吗?
【问题讨论】:
-
你为什么没有一个
@Before方法来重新实例化你的WebDriver类? -
因为在我的 TestGoogleHomePage 类中,我使用 public TestGoogleHomePage() { super(); } 来初始化我的 Webdriver 类,如果我将 \@Before 放在这个构造函数上,它会抱怨 @before 位于非法位置。但似乎它总是会为每个测试重新初始化 Webdrive 类,即使没有 \@before。
标签: java junit webdriver selenium-webdriver