适用于Chrome的Selenium网络驱动程序未在指定的路径中保存屏幕截图

时间:2018-10-26 07:53:07

标签: java selenium google-chrome selenium-webdriver webpage-screenshot

public void afterTestMethod(TestContext testContext) throws Exception {
    if (testContext.getTestException() == null) {
        return;
    }
    File screenshot = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
    String testName = testContext.getTestClass().getSimpleName();
    String methodName = testContext.getTestMethod().getName();
    Files.copy(screenshot.toPath(),
    Paths.get("C:\\Users\\user\\git\\ufe-360\\UFE-TESTS\\screenshots\test.png", testName + "_" + methodName + "_" + screenshot.getName())); 
    } 
}

我的项目中有上面的代码,可以在测试执行后拍摄屏幕截图。 我怀疑我的代码中缺少某些内容。当我运行每个测试屏幕截图时,请不要将其保存在指定的路径中。我没有任何错误。每个测试都能正确执行,但没有屏幕截图。

2 个答案:

答案 0 :(得分:2)

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;


        private static void takeScreenshot() throws IOException, InterruptedException {
            // TODO Auto-generated method stub

            System.setProperty("webdriver.chrome.driver", "chromedriver");              
            driver = new ChromeDriver();

            driver.get("https://www.google.com/");
            Thread.sleep(2);

            TakesScreenshot scrShot =((TakesScreenshot)driver);
            File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
            File DestFile=new File("/home/XXXX/Desktop/test.png");
            FileUtils.copyFile(SrcFile, DestFile);      

        }   

以上代码将打开“ google.com”,它将截取屏幕截图并将其存储在桌面上,就像我给定的桌面路径一样。

答案 1 :(得分:0)

在方法开始时,您拥有的代码将在测试没有错误/异常时不让屏幕截图完成。因此,您说“每个测试都能正确执行,但没有屏幕截图。”这是完全可以预期的。 来自一个问题:

if (testContext.getTestException() == null) {
    return;
}

从您的其他评论中

if (ITestResult.FAILURE == result.getStatus()) {

您的逻辑如下:如果测试失败,请在失败时制作屏幕截图。尝试修改测试代码以使其失败,您应该在给定的路径中看到屏幕截图。如果要实现“在每个测试步骤都制作一张屏幕截图”之类的不同逻辑,请更正一个问题,因为它将有一些不同的解决方案。

如果您仅删除if逻辑,则您的代码将在测试的最后一步之后生成屏幕截图。 (但我不确定此类屏幕截图是否非常有用,因为通常使用屏幕截图来帮助分析“出了什么问题”,并且您的逻辑可以完美地覆盖它)