小编给大家分享一下如何实现Selenium的UI自动化测试屏幕截图功能,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
UI自动化测试执行过程中,当遇到检查失败的情况,往往会发现打印的log并不能有效地帮助我们定位问题。我们需要失败时刻的屏幕截图来重现当时的失败场景,进而排查出错原因。
基于这种需求可以使用Selenium的屏幕截图功能。
实现代码如下:
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.interactions.Actions;
public static void takeScreeshot(String screenPath, WebDriver chrome){
try {
//指定了OutputType.FILE做为参数传递给getScreenshotAs()方法,其含义是将截取的屏幕以文件形式返回。
File scrFile = ((TakesScreenshot) chrome)
.getScreenshotAs(OutputType.FILE); // 关键代码,执行屏幕截图,默认会把截图保存到temp目录
FileUtils.copyFile(scrFile, new File(screenPath)); //利用FileUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件对象。
} catch (IOException e) {
System.out.println("Screen shot error: " + screenPath);
System.out.println("该错误可以查看截图:"+screenPath);
} catch (Exception e) {
// TODO: handle exception
}
}
public static void takeScreenshot(WebDriver chrome,String imgName) {
String screenName=imgName+DateUtils.MILLIS_PER_DAY+".jpg";
String fileString= "D:\\selenium\\SchoolpalERP_QTP\\image";
if (!(new File(fileString).isDirectory())) { // 判断是否存在该目录
new File(fileString).mkdir(); // 如果不存在则新建一个目录
}
File dir = new File(fileString);
if (!dir.exists())
dir.mkdirs();
String screenPath = dir.getAbsolutePath() + "\\" + screenName;
takeScreeshot(screenPath, chrome);
}
以上是“如何实现Selenium的UI自动化测试屏幕截图功能”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。