Exception handling Selenium 2和JUnit4:如何捕获异常屏幕截图?

Exception handling Selenium 2和JUnit4:如何捕获异常屏幕截图?,exception-handling,junit,selenium-webdriver,junit4,Exception Handling,Junit,Selenium Webdriver,Junit4,我只想在出现意外异常时捕获屏幕截图。注意。-此答案可能已过时。答案基于硒2.15 使用该技巧(单元测试必须扩展以下BaseTest): 公共抽象类BaseTest{ // ... 受保护的网络驱动程序; @统治 公共TestRule testWatcher=新的testWatcher(){ @凌驾 公共无效开始(描述说明){ LOG.info(“启动浏览器…”); driver=Utils.getFirefoxDriver(); } @凌驾 已完成公共作废(描述说明){ LOG.info(“退出

我只想在出现意外异常时捕获屏幕截图。

注意。-此答案可能已过时。答案基于硒2.15

使用该技巧(单元测试必须扩展以下
BaseTest
):

公共抽象类BaseTest{
// ...
受保护的网络驱动程序;
@统治
公共TestRule testWatcher=新的testWatcher(){
@凌驾
公共无效开始(描述说明){
LOG.info(“启动浏览器…”);
driver=Utils.getFirefoxDriver();
}
@凌驾
已完成公共作废(描述说明){
LOG.info(“退出驱动程序…”);
driver.quit();
}
@凌驾
公共作废失败(可丢弃e,说明d){
调试(“创建屏幕截图…”);
文件scrFile=((TakesScreenshot)驱动程序).getScreenshotAs(
OutputType.FILE);
字符串scrFilename=“Screenshot.png”;
文件输出文件=新文件(屏幕\快照\结果\路径,scrFilename);
LOG.info(scrFilename+“创建的屏幕截图”);
试一试{
组织。​阿帕奇。​平民​io.FileUtils.copyFile(scrFile,outputFile);
}捕获(ioe异常ioe){
LOG.error(“异常后复制屏幕截图时出错。”,ioe);
}
}
};
}

Utils.getFirefoxDriver()
返回自定义的
WebDriver
。比如:

import org.openqa.selenium.WebDriver;
导入org.openqa.selenium.firefox.FirefoxBinary;
导入org.openqa.selenium.firefox.FirefoxDriver;
导入org.openqa.selenium.firefox.FirefoxProfile;
公共类UTIL{
// ...
公共静态WebDriver getFirefoxDriver(){
FirefoxProfile FirefoxProfile=新的FirefoxProfile();
//配置文件自定义。例如:
//firefoxProfile.addExtension(“firebug-1.8.4-fx.xpi”);
//setPreference(“extensions.firebug.currentVersion”,“1.8.4”);
FirefoxBinary firefox=新的FirefoxBinary();
//Firefox自定义。例如:
//setEnvironmentProperty(“DISPLAY”,DISPLAY);
WebDriver驱动程序=新的FirefoxDriver(firefox、firefoxProfile);
//WebDriver自定义。例如:
//driver.manage().timeouts().implicitlyWait(SHORT\u TIMEOUT\S,TimeUnit.SECONDS);
返回驱动器;
}
}

您应该将您的解决方案作为实际答案发布(稍后您可以接受)。你的问题似乎已经解决了。谢谢你的建议。JUnit已经不推荐TestWatchman而支持TestWatcher。我找不到
Utils.getFirefoxDriver()。这是否已被删除,或者这是您自己的实现?如何获得正确的驱动程序实例?@vanto这是我自己的实现。我已经对我的回答做了澄清。@mikeslattery谢谢你的通知。我已经更新了答案。我运行的第二个问题是:我的驱动程序实例不能转换为
截图。幸运的是,它通过以下方式增强了驱动程序:
WebDriver augmentedDriver=new Augmenter().augment(driver)并使用
augmentedDriver
进行铸造。在此处找到此解决方案: