近要在框架中添加case失败时,要自动截图,坐下总结。
1.只针对webdriver的异常截图,重写onException,该方法由于只针对webdriver抛的异常时才能截图,有一定的限制
public void onException(java.lang.Throwable throwable,
WebDriver driver){
Throwable cause = throwable.getCause();
/*
String cause = throwable.getClass().getName();
ScreenshotException ec = new ScreenshotException(cause);
*/
System.out.println(throwable.getClass().getName());
System.out.println("onException=" + cause);
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
String dateString = formatter.format(currentTime);
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
File screenshot = new File("D:/ddd/"
+ dateString + ".png");
FileUtils.copyFile(scrFile,screenshot);
} catch (IOException e) {
e.printStackTrace();
}
}
测试类,要用EventFiringWebDriver ,并注册MyListen
public static void main(String args[]) {
String key = "webdriver.chrome.driver";
String value = "D:/BaiduYunDownload/selenium/chromedriver.exe";
System.setProperty(key, value);
WebDriver dr = new ChromeDriver();
EventFiringWebDriver event = new EventFiringWebDriver(dr);
MyListen ml = new MyListen();
event.register(ml);
dr = event;
dr.get("http://www.baidu.com");
dr.findElement(By.id("kw1")).sendKeys("test");
//System.out.println(5/0);
Assert.assertEquals("haha", event.findElement(By.id("su")).getAttribute("value"));
event.quit();
}