Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Webdriver 2.28 automatically take a screenshot on exception/fail/error?

Does Webdriver 2.28 automatically take a screenshot on exception/fail/error?

If it does, where can I find the screenshot? Which directory is the default?

like image 936
Tingting Avatar asked Feb 04 '13 16:02

Tingting


2 Answers

No, it doesn't do it automatically. Two options you can try:

  1. Use WebDriverEventListener that is attachable to a EventFiringWebDriver which you can simply wrap around your usual driver. This will take a screenshot for every Exception thrown by the underlying WebDriver, but not if you fail an assertTrue() check.

    EventFiringWebDriver driver = new EventFiringWebDriver(new InternetExplorerDriver());
    WebDriverEventListener errorListener = new AbstractWebDriverEventListener() {
        @Override
        public void onException(Throwable throwable, WebDriver driver) {
            takeScreenshot("some name");
        }
    };
    driver.register(errorListener);
    
  2. If you're using JUnit, use the @Rule and TestRule. This will take a screenshot if the test fails for whatever reason.

    @Rule
    public TestRule testWatcher = new TestWatcher() {
        @Override
        public void failed(Throwable t, Description test) {
            takeScreenshot("some name");
        }
    };
    

The takeScreenshot() method being this in both cases:

public void takeScreenshot(String screenshotName) {
    if (driver instanceof TakesScreenshot) {
        File tempFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(tempFile, new File("screenshots/" + screenshotName + ".png"));
        } catch (IOException e) {
            // TODO handle exception
        }
    }
}

...where the FileUtils.copyFile() method being the one in Apache Commons IO (which is also shipped with Selenium).

like image 77
Petr Janeček Avatar answered Sep 28 '22 11:09

Petr Janeček


WebDriver does not take screenshot itself. But you cat take by this way : ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);

Then save the screenshot anywhere you want.

Also you cat use something like Thucydides, wich may take screenshot on each action or on error and put it in a pretty report.

like image 31
Pazonec Avatar answered Sep 28 '22 11:09

Pazonec