Selenium 失败截图方法实现浅谈

因为我用的是selenium webdriver+Eclipse+TestNG的解决方案,之前也在网上看到过很多关于失败截图的方法。不知道在哪看过一篇文章,说一个Tester的截图就应该像诗人能“吟的一首好诗”一样“截的一手好图”, :lol: 而我看到的方法大多是基于Webdriver Exception,和调用EventListener相结合。下面我简单就我的经验将截图方法分类总结一下:
在说正题之前,先给出一个比较通用的常用截图方法,这个用过selenium的人就不用我多说了吧。基本上各种教程,例程给出的方法都大抵相同。而我们要实现的各种失败的方法也源于此,后续再谈。
public static void screenShot(WebDriver driver, String desc) {
  Date currentTime = new Date();
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
  String dateString = formatter.format(currentTime);
  File scrFile = ((TakesScreenshot) driver)
  .getScreenshotAs(OutputType.FILE);
  try {
  desc = desc.trim().equals("") ? "" : "-" + desc.trim();
  File screenshot = new File("screenshot" + File.separator
  + dateString + desc + ".png");
  FileUtils.copyFile(scrFile, screenshot);
  } catch (IOException e) {
  e.printStackTrace();
  }
  }
其实我们完全可以利用此方法,定制出我们想要的截图方法去方便程序调用,比如:
public void getScreenshot(WebDriver driver)
{

Date date1=new Date();
String h=String.format("%tH", date1);
String m=String.format("%tM", date1);
String s=String.format("%tS", date1);
String d=String.format("%tF", date1);
String PathOfSnapshot = "E:/JAVA testing/";
String SnapshotName = d+"_"+h+m+s + ".png";

PathOfSnapshot = PathOfSnapshot + SnapshotName;
//Selenium.CaptureScreenshot(PathOfError);
File screenShotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

try
{
FileUtils.copyFile(screenShotFile, new File(PathOfSnapshot));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

}
这样就可以定制一个文件名为日期-时间的截图方法,截图后也可以方便我们到log查找,定位问题

Ok,接下来重点来了,我们需要在失败为判断节点的情况下,调用此方法,这样就需要用ITsetResult这个Testng的接口了,具体方法如下:
@AfterMethod
public void afterMethod(ITestResult result, Method method) {

afterInvocation(result, method);
driver.close();

}
然后我们定义afterInvocation方法:
public void afterInvocation(ITestResult result, Method method)
{
if (!result.isSuccess()) {

File f = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
Date date1=new Date();
String h=String.format("%tH", date1);
String m=String.format("%tM", date1);
String s=String.format("%tS", date1);
String d=String.format("%tF", date1);
String PathOfSnapshot = "E:/JAVA testing/FailCases/";
String SnapshotName = d+"_"+h+m+s + ".png";
PathOfSnapshot = PathOfSnapshot + SnapshotName;
try {
FileUtils.copyFile(f, new File(PathOfSnapshot));
System.out.println("This is a fail test case"+ method.getName());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
方法中的截图和上例几乎一样,只不过把路径改一下就可以了,另外加上了失败的方法名方便我们定位。个人经验之谈,谈不上有多么高深,只是大家能方便自己用就好,方法是死的,人是活的,项目也是活的,大家如果都在摸索阶段,能提供大家一些思路和方法做参考就好。如果是高手了,也希望我抛砖引玉,能把这个话题一直延续下去讨论交流。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值