自动化用例是由程序去执行,因此有时候打印的错误信息并不十分明确。如果在脚本执行出错的时候能对当前窗口截图保存,那么通过图片就可以非常直观地看出出错的原因。WebDriver 提供了截图函数getScreenshotAs()来截取当前窗口。
根据虫师的demo,我结合实际做了优化,效果不错。抛异常后截图,并且截图以时间戳命名区分。
package ScreenShot;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ScreenShotCSDN {
public static void main(String[] args) throws IOException {
WebDriver driver = new FirefoxDriver();
// 打开CSDN登录页面
driver.get("https://passport.csdn.net/account/login?ref=toolbar");
try {
//输入用户名和密码,此处专门将密码输入错误,造出异常现象
driver.findElement(By.xpath(".//*[@id='username']")).sendKeys("ab_2016");
driver.findElement(By.xpath(".//*[@id='password']")).sendKeys("aaa");
driver.findElement(By.xpath(".//*[@id='fm1']/input[6]")).click();
// 由于密码输入错误,所以无法进入登陆后页面,也就无法进行点击“设置”的操作,因此如我们所愿,进入catch分支
driver.findElement(By.linkText("设置")).click();
} catch (Exception e) {
// 打印异常原因,控制台也会打印
System.out.println("======exception reason=======" + e);
//图片名称加时间戳
String dateString = getDateFormat();
// getScreenshotAs()对当前窗口进行截图
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// 需要指定图片的保存路径及文件名
FileUtils.copyFile(srcFile, new File("e:\\selenium\\" + dateString + ".png"));
e.printStackTrace();
}
}
public static String getDateFormat(){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
String dateString = sdf.format(date);
return dateString;
}
}