Is it possible to set up webdriver so that when an error is encountered, a screen capture can be taken?
Asked
Active
Viewed 2,384 times
2
-
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 Answers
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
-
Is there any way of causing this code to be run upon encountering an error? – user3083447 Dec 09 '13 at 16:47
-
-
-
commonsIO from here - http://commons.apache.org/proper/commons-io/javadocs/api-release/index.html?org/apache/commons/io/package-summary.html – Bosko Mijin Dec 09 '13 at 17:22