Capture screenshots when Selenium tests fail

This blog continues on my last blog on Selenium and demonstrates how to setup Junit4 to capture screenshots of the browser when  tests fail.

Create JUnit Rule

First, the rule in which JUnit uses to run and report test methods needs to be updated. This is done by implementing the interface org.junit.rules.MethodRule. JUnit provides a base class TestWatchman where we can extend:

public class ScreenShotRule extends TestWatchman {

 public void failed(Throwable e, FrameworkMethod method) {
 // capture screenshot here

Capture screenshots with Selenium

Selenium WebDriver implements the interface TakesScreenshot which indicates the web driver has the capability to capture screenshots. To enable this, the RemoteWebDriver instance needs to be augmented as below.

// In class AbstractRCTest (see my previous blog)
driver = new RemoteWebDriver(remoteUrl, capabilities);

 // Augment web driver for screenshot capture
 WebDriver augmentedDriver = new Augmenter().augment(driver);
 screenShotRule = new ScreenShotRule(augmentedDriver);

Now we can implement screenshot capture in class ScreenShotRule to take screenshots with Selenium and save it to file:

 public void failed(Throwable e, FrameworkMethod method) {
      File scrFile = ((TakesScreenshot) webdriver).getScreenshotAs(
      String scrFilename = method.getName() + "-Screenshot.png";
      File outputFile = new File("C:\\Temp", scrFilename);
      try {
           FileUtils.copyFile(scrFile, outputFile);
      } catch (IOException ioe) {
           log.error("Error copying screenshot after exception.", ioe);

Add rule to JUnit test class

Last thing to do is to set new rule in the unit test class

public class SampleRemoteTest {
     public ScreenShotRule screenShotRule;

That’s it. Now if a test fails, a screenshot will be taken of the browser in the server machine and saved into a local client where the test is run.

About Raymond Lee
Professional Java/EE Developer, software development technology enthusiast.

Comments are closed.