您的位置:首页 > 产品设计 > UI/UE

基于Selenium的UI自动化测试屏幕截图功能实践

2015-02-01 16:29 302 查看
http://qa.blog.163.com/blog/static/19014700220123643719638/

UI自动化测试执行过程中,当遇到检查失败的情况,往往会发现打印的log并不能有效地帮助我们定位问题。我们需要失败时刻的屏幕截图来重现当时的失败场景,进而排查出错原因。

基于这种需求,调研了下Selenium的屏幕截图功能。使用起来很方便,我自己封装了一个静态方法,关键部分是try包含的代码。实现代码如下:

Selenium2.0(WebDriver)实现

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

public static void screenShot(WebDriver driver) {

String dir_name = "screenshot"; // 这里定义了截图存放目录名
if (!(new File(dir_name).isDirectory())) { // 判断是否存在该目录

new File(dir_name).mkdir(); // 如果不存在则新建一个目录
}

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
String time = sdf.format(new Date()); // 这里格式化当前时间,例如20120406-165210,后面用的着

try {

File source_file = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // 关键代码,执行屏幕截图,默认会把截图保存到temp目录

FileUtils.copyFile(source_file, new File(dir_name + File.separator + time + ".png")); // 这里将截图另存到我们需要保存的目录,例如screenshot\20120406-165210.png
} catch (IOException e) {

e.printStackTrace();
}
}

另外值得一提的是,这样截出来的图,如果页面过长出现滚动条,是会把完整的页面都截取的。

Selenium1.0实现

Selenium selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.com.hk");
selenium.start();
selenium.open("http://www.google.com.hk/");
selenium.windowMaximize();
selenium.windowFocus();
selenium.captureEntirePageScreenshot("screenshot.png", "");

似乎只能在Selenium RC上运行,以及Firefox浏览器。。Selenium1.0有个CaptureScreenshot方法也能实现屏幕截图。CaptureScreenshot截取浏览器内可见部分,而captureEntirePageScreenshot截取浏览器内所有内容。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: