当前位置: 移动技术网 > IT编程>开发语言>Java > 关于Selenium的UI自动化测试屏幕截图功能实例代码

关于Selenium的UI自动化测试屏幕截图功能实例代码

2019年07月19日  | 移动技术网IT编程  | 我要评论

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自动化测试屏幕截图功能实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网