使用Appium截取Android屏幕截图

7

我目前已经使用Java和JUnit在Appium测试中实现了iOS截图功能。在测试结束之前,代码会运行以获取屏幕上最后可见的内容,然后关闭连接。

@After
public void tearDown() throws Exception {
    if (platform.equals(iOS)) {
        captureScreenshot(testName.getMethodName());
    }
    driver.quit();
}

@SuppressWarnings("Augmenter")
public void captureScreenshot(String testName) {
    String imagesLocation = "target/surefire-reports/screenshot/" + platform + "/";
    new File(imagesLocation).mkdirs(); // Insure directory is there
    String filename = imagesLocation + testName + ".jpg";

    try {
        Thread.sleep(500);
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File scrFile = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File(filename), true);
    } catch (Exception e) {
        System.out.println("Error capturing screen shot of " + testName + " test failure.");
        // remove old pic to prevent wrong assumptions
        File f = new File(filename);
        f.delete(); // don't really care if this doesn't succeed, but would like it to.
    }
}

这在安卓上有点用,但最近它完全破坏了正在运行的测试,但这可能与它试图获取快照的设备有关。以前它会保存文件,但图像会出现空白或损坏。
有人知道如何使用appium在安卓上实现图像/屏幕捕获吗?也许可以使用UIAutomator?

你尝试过不带'true'参数的方式吗:FileUtils.copyFile(scrFile, new File(filename), true); 并且使用最新的Appium吗?我正在使用非常相似的代码,对我来说它很好用。 - HRVHackers
2个回答

12

你可以使用这种方法:

public void screenshot(String path_screenshot) throws IOException{
    File srcFile=driver.getScreenshotAs(OutputType.FILE);
    String filename=UUID.randomUUID().toString(); 
    File targetFile=new File(path_screenshot + filename +".jpg");
    FileUtils.copyFile(srcFile,targetFile);
}

对我来说它很好用。


我的也很好用。干杯! - Nisim Naim
以上代码对我来说运行良好。 - Ripon Al Wasim

4

我在谷歌搜索中发现了这篇文章,与我的问题几乎一样:在Android模拟器上使用Appium截图时,截到的图片是空白的。我既尝试了你描述的“原生”方法,也使用了ATU框架中提供的方法。

WebElement appArea = wd.findElementByXPath("//android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]");
ATUReports.add("Main Screen Area Screenshot", LogAs.INFO, new CaptureScreen(appArea));

两者都返回空白/透明。好消息是,这个空白/透明图像的尺寸恰好是我想要捕获的尺寸 - 避免了状态栏,在图像比较中导致日期差异错误的问题。话虽如此,如果没有实际可见像素(用于最终匹配对象区域抓取到已验证的基线图像),它就没有多大用处。

我尝试将上下文设置为“NATIVE_APP”,但并没有有效果。总之,我感到很困扰。如果您在这方面有任何进展,我很乐意阅读/听取您如何使其正常工作的方式。也许下一步是转到Appium Google Group。

编辑:我发现了我的核心问题 - 使用HAXM加速会导致空白的截屏。请注意,如果测试的能力中的基础设备配置文件定义为选择了“Host GPU”,这也会影响在物理设备上运行的测试。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接