selenium2 斷言失敗自動截圖 (四)


一般web應用程序出錯過后,會拋出異常。這個時候能截個圖下來,當然是極好的。

selenium自帶了截圖功能。

            //獲取截圖file
            File scrFile= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            //將圖片移動到指定位置
            FileUtils.moveFile(scrFile, new File(newFilePath));

當然在截圖之前 需要判斷新路徑是否合法。下面貼出整體的代碼。

package common;
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.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class ScreenShot {
    public WebDriver driver;
    public ScreenShot(WebDriver _driver){
        driver=_driver;
    }
    private void takeScreenshot(String screenPath){
        try {
            //獲取截圖file
            File scrFile= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            //將圖片移動到指定位置
            FileUtils.moveFile(scrFile, new File(screenPath));
        }  catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void takeScreenshot(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd(hh_mm_ss)SSS");
        String fileName=dateFormat.format( new Date());
        //創建新的文件名
        String screenName=fileName+".jpg";
        //創建文件夾
        File dir = new File("test-output/snapshot");
        if (!dir.exists()){
            dir.mkdirs();
        }
        //獲取新文件名的絕對路徑
        String screenPath= dir.getAbsolutePath()+"/"+screenName;
        //截圖
        this.takeScreenshot(screenPath);
    }
}

調用

ScreenShot ss = new ScreenShot(Driver);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM