截屏实现方法如下
public static void screenshot(AndroidDriver driver, String pictureName) {
try {
String os_name = System.getProperty("os.name");
String dir_name = System.getProperty("user.dir");
File screenshot = driver.getScreenshotAs(OutputType.FILE);
if (os_name.equals("Linux") || os_name.equals("Mac OS X")) {
dir_name = dir_name + "/target/screenshot/";
dirIsExists(dir_name);//判断目录是否存在,不存在则重新创建
} else if (os_name.equals("Windows 7") || os_name.equals("Windows 10")) {
dir_name = dir_name + "\\target\\screenshot\\";
dirIsExists(dir_name);//判断目录是否存在,不存在则重新创建
}
FileUtils.copyFile(screenshot, new File(dir_name + pictureName + FormatTime.getCurrentTime() + ".jpg"));
} catch (Exception e) {
}
}
/**
* 判断文件夹是否存在,不是则创建文件夹
*/
private static void dirIsExists(String dirPath) {
File dir = new File(dirPath);
if (!dir.isDirectory()) {
dir.mkdirs();
}
}
}
调用截屏方法
执行test后在after Method中加入截屏操作,如下:
@AfterMethod
private void logout(ITestResult iTestResult){ //ITestResult 中存有test执行结果
int status = iTestResult.getStatus();
String method = iTestResult.getMethod().getMethodName();
//执行失败,屏幕截图
if(status == ITestResult.FAILURE){
ScreenShot.screenshot(driver, method);
}
}