Capturing ScreenShots Failed Selenium Test Cases

In this example we will show you how to capture screenshots failed selenium test cases. It can be quite tricky to see why a selenium test has failed. That’s why it is also great to have some more information about why the selenium test failed. One improvement could be taking a screenshot of the failed test which we will explain here. Another solution is to make a video recording of your tests.

Capturing ScreenShots Failed Selenium Test

With the MethodRule of JUnit we can intercept failed unit tests before JUnit sends out the results. This is the perfect lifecycle event to take the opportunity to take a screen shot of why the test failed.

package com.memorynotfound.test;

import java.util.UUID;

import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public class ScreenShotOnFailure implements MethodRule {

    private WebDriver driver;

    public ScreenShotOnFailure(WebDriver driver){
        this.driver = driver;

    public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o) {
        return new Statement() {
            public void evaluate() throws Throwable {
                try {
                } catch (Throwable t) {
                    // exception will be thrown only when a test fails.
                    // rethrow to allow the failure to be reported by JUnit
                    throw t;

            public void captureScreenShot(String fileName) throws IOException {
                File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
                fileName += UUID.randomUUID().toString();
                File targetFile = new File("/tmp/" + fileName + ".png");
                FileUtils.copyFile(scrFile, targetFile);

Apply The rule in Selenium Test

We can register our custom MethodRule by annotating it with @Rule. Then sit back and see the magic happen.

package com.memorynotfound.test;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import static org.junit.Assert.assertTrue;

public class ScreenShotTest {

    private static WebDriver driver;

    public ScreenShotOnFailure failure = new ScreenShotOnFailure(driver);

    public static void setUp(){
        driver = new FirefoxDriver();

    public void testTakeScreenShot() throws IOException {

    public static void cleanUp(){
        if (driver != null){




You may also like...