Reputation: 157
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?
Upvotes: 8
Views: 9900
Reputation: 38424
No, it doesn't do it automatically. Two options you can try:
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);
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).
Upvotes: 11
Reputation: 1788
The short answer is No. WebDriver is an API to interact with the browser. You can make screenshots with it but you should know when to do it. So it's not done automatically as WebDriver doesn't know anything about testing.
If you are using TestNG as testing library you can implement Listener whose methods will be executed on different events (failure, success or other). In these methods you can implement the required logic (e.g. making screenshots).
Upvotes: 1
Reputation: 1559
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.
Upvotes: 2