导航

Appium框架之截图实现

Posted on 2017-07-31 21:15  Young哥哥  阅读(608)  评论(0)    收藏  举报

我们继续研究Appium,今天我们要实现的是截图功能。自动化框架中的截图功能是一个很方便很实用的功能,用过QTP的朋友一定会注意到,从最简单的录制回放中,可以看到QTP对关键点的的截图,能够让查看测试报告的人一目了然的看到你测试执行的情况,也是做对比和验证的一个依据。

 

那么如何实现Appium截图呢? 其实Appium的截图功能是借助于TakesScreenshot接口

AppiumDriver继承Selenium的RemoteWebDriver,因此直接使用TakeScreenshot接口(⚠️shot是小写字母开头)。那么怎么用呢?
首先通过生成截图:
File screenShort=driver.getScreenshotAs(OutputType.FILE)
然后把截图保存到指定路径:
FileUtils.copyFile(screenShot, new File(newPath));
我这里封装一个截图方法:
/**
* This Method create for take screenshot
* 
* @author Young
* @param drivername
* @param filename
*/
public static void snapshot(TakesScreenshot drivername, String filename) {
// this method will take screen shot ,require two parameters ,one is
// driver name, another is file name
String currentPath = System.getProperty("user.dir"); // get current work
File scrFile = drivername.getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy
// somewhere
try {
System.out.println("save snapshot path is:" + currentPath + "/"
+ filename);
FileUtils
.copyFile(scrFile, new File(currentPath + "\\" + filename));
} catch (IOException e) {
System.out.println("Can't save screenshot");
e.printStackTrace();
} finally {
System.out.println("screen shot finished, it's in " + currentPath
+ " folder");
}
}

  

而这种方式截图需要主动调用,不能够在测试失败自动截图。大多数情况我们的需求往往是失败的时候实现自动截图,知道挂在什么地方,哪个页面。那么如何实现失败截图呢?

原理很简单,前提是你得使用testng,override一下TestListenerAdapter,在

onTestFailure方法中添加截图方法。