是否可以设置Selenium Webdriver在遇到错误时进行屏幕捕获

时间:2013-12-09 16:36:21

标签: java firefox selenium webdriver screenshot

是否可以设置webdriver以便在遇到错误时可以进行屏幕捕获?

2 个答案:

答案 0 :(得分:3)

如果您正在运行JUnit,则可以设置规则以在失败时截取屏幕截图。对于TestNG,有类似的方法。

<强> Event.java

public static void takeScreenshot(WebDriver driver, String name) throws IOException {
if (driver instanceof TakesScreenshot) {
    File tempFile = ((TakesScreenshot) driver)
            .getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(tempFile, new File(String.format("screenshots/%s.png", name)));
    }
}

<强> ScreenshotOnFailRule.java

public class ScreenshotOnFailRule extends TestWatcher {

    private static boolean shouldStopTests = false;

    @Override
    public void failed(Throwable e, Description d) {
        try {
            Event.takeScreenshot(yourDriver, "Failure");
        } catch (IOException ioe) {
            log.error("Test didn't finish due to hard failure.");
            shouldStopTests = true;
        }
        if (shouldStopTests) {
            System.exit(0);
        }
}

然后在测试课开始时:

    @Rule
    public TestRule screenshot = new ScreenshotOnFailRule();

答案 1 :(得分:0)

当然,这是可能的。这是一个例子:

WebDriver firefoxDriver = new FirefoxDriver();
firefoxDriver.get("http://www.google.com/");
File scrsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrsht, new File("your_path/screenshot.png"));