UI自动化测试执行过程中,当遇到检查失败的情况,往往会发现打印的log并不能有效地帮助我们定位问题。我们需要失败时刻的屏幕截图来重现当时的失败场景,进而排查出错原因。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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(); } } |
1 2 3 4 5 6 |
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的UI自动化测试屏幕截图功能实践
-----==== 本站公告 ====-----
1.本站是目前唯一能支持智能手机平板电脑访问的软件测试技术网站.
2.具体访问方法请参考本站的手机访问说明,或直接点击以下链接:
→点击这里打开手机平板访问说明←