在功能自动化测试脚本中加上截图功能,方便分析测试结果。
Web截图代码
protected static WebDriver driver;
public static void getScreenShot(String fileName) {
File screenshot = null;
if (!(driver instanceof TakesScreenshot)) {
WebDriver augmentDriver = new Augmenter().augment(driver);
screenshot = ((TakesScreenshot) augmentDriver).getScreenshotAs(OutputType.FILE);
} else
screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
fileName = "C:\\screenShot\\"+ fileName + ".png";
try {
FileInputStream imgIs = new FileInputStream(screenshot);
FileOutputStream imageOs = new FileOutputStream(new File(fileName));
FileChannel imgCin = imgIs.getChannel();
FileChannel imgCout = imageOs.getChannel();
imgCin.transferTo(0, imgCin.size(), imgCout);
imgCin.close();
imgCout.close();
imgIs.close();
imageOs.close();
} catch (IOException e) {
System.out.println("截图失败,错误信息为:" + e.getMessage());
}
}
安卓截图代码
protected static AndroidDriver androidDriver;
public static void getScreenShot(String fileName) {
File screenshot = androidDriver.getScreenshotAs(OutputType.FILE);
fileName = "C:\\screenShot\\"+ fileName + ".png";
try {
FileInputStream imgIs = new FileInputStream(screenshot);
FileOutputStream imageOs = new FileOutputStream(new File(fileName));
FileChannel imgCin = imgIs.getChannel();
FileChannel imgCout = imageOs.getChannel();
imgCin.transferTo(0, imgCin.size(), imgCout);
imgCin.close();
imgCout.close();
imgIs.close();
imageOs.close();
} catch (IOException e) {
System.out.println("截图失败,错误信息为:" + e.getMessage());
}
}
在点击元素的过程中加入截图功能
public static void click(By element){
try{
driver.findElement(element).click();
}catch(Exception e){
getScreenShot(element.toString());
throw new NoSuchElementException("点击元素失败!");
}
}
若点击失败,截图在C:\screenShot文件夹下面保存。