自動化用例是由程序去執行,因此有時候打印的錯誤信息並不十分明確。如果在腳本執行出錯的時候能對當前窗口截圖保存,那麼通過圖片就可以非常直觀地看出出錯的原因。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;
}
}