2

Is it possible to set up webdriver so that when an error is encountered, a screen capture can be taken?

user3083447
  • 147
  • 1
  • 3
  • 15
  • okey, what you are looking for is already may be [here][1] [1]: http://stackoverflow.com/questions/8642376/is-it-possible-to-capture-a-screen-shot-for-a-webelement-directly-by-using-webdr?rq=1 – neshpro9 Dec 09 '13 at 16:41
  • Was wanting the screen shot to be taken only in the case of an error being thrown. – user3083447 Dec 09 '13 at 16:45

2 Answers2

3

If you are running JUnit, you can set up a Rule to take a screenshot on failure. There is a similar way to do this for 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);
        }
}

Then at the start of your test class:

    @Rule
    public TestRule screenshot = new ScreenshotOnFailRule();
NaviSaysListen
  • 421
  • 4
  • 7
0

Of course, it is possible. Here is the example:

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"));
Bosko Mijin
  • 3,287
  • 3
  • 32
  • 45