关于Selenium的UI自动化测试屏幕截图功能实例代码
UI自动化测试执行过程中,当遇到检查失败的情况,往往会发现打印的log并不能有效地帮助我们定位问题。我们需要失败时刻的屏幕截图来重现当时的失败场景,进而排查出错原因。
基于这种需求可以使用Selenium的屏幕截图功能。
实现代码如下:
importjava.io.File;
importjava.io.IOException;
importorg.apache.commons.io.FileUtils;
importorg.apache.commons.lang3.time.DateUtils;
importorg.openqa.selenium.OutputType;
importorg.openqa.selenium.TakesScreenshot;
importorg.openqa.selenium.WebDriver;
importorg.openqa.selenium.interactions.Actions;
publicstaticvoidtakeScreeshot(StringscreenPath,WebDriverchrome){
try{
//指定了OutputType.FILE做为参数传递给getScreenshotAs()方法,其含义是将截取的屏幕以文件形式返回。
FilescrFile=((TakesScreenshot)chrome)
.getScreenshotAs(OutputType.FILE);//关键代码,执行屏幕截图,默认会把截图保存到temp目录
FileUtils.copyFile(scrFile,newFile(screenPath));//利用FileUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件对象。
}catch(IOExceptione){
System.out.println("Screenshoterror:"+screenPath);
System.out.println("该错误可以查看截图:"+screenPath);
}catch(Exceptione){
//TODO:handleexception
}
}
publicstaticvoidtakeScreenshot(WebDriverchrome,StringimgName){
StringscreenName=imgName+DateUtils.MILLIS_PER_DAY+".jpg";
StringfileString="D:\\selenium\\SchoolpalERP_QTP\\image";
if(!(newFile(fileString).isDirectory())){//判断是否存在该目录
newFile(fileString).mkdir();//如果不存在则新建一个目录
}
Filedir=newFile(fileString);
if(!dir.exists())
dir.mkdirs();
StringscreenPath=dir.getAbsolutePath()+"\\"+screenName;
takeScreeshot(screenPath,chrome);
}
以上这篇关于Selenium的UI自动化测试屏幕截图功能实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。