Java Selenium - ScreenshotUtil

Snippet Testing

Reusable ScreenshotUtil implementation for capturing browser, element, and failure screenshots in Selenium automation

What is this? Official Docs

Reusable Java utility for capturing browser, element, and failure screenshots in Selenium-based automation frameworks.

What is ScreenshotUtil?

ScreenshotUtil is a reusable Selenium utility that standardizes screenshot capturing across automation frameworks. It helps testers capture browser, element-level, and failure screenshots for debugging, reporting, and audit purposes.

📸 Java - ScreenshotUtil Base Class

Central utility class to capture screenshots using Selenium WebDriver.

import org.openqa.selenium.*;
import org.openqa.selenium.io.FileHandler;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ScreenshotUtil {

    private static final String SCREENSHOT_DIR = "screenshots/";

    private static String getTimestamp() {
        return new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    }

    private static File createDirectoryIfNotExists() {
        File dir = new File(SCREENSHOT_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    public static String captureBrowserScreenshot(WebDriver driver, String name) {
        createDirectoryIfNotExists();
        String path = SCREENSHOT_DIR + name + "_" + getTimestamp() + ".png";
        File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        try {
            FileHandler.copy(src, new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
}

🎯 Java - Element Screenshot Capture

Capture screenshot of a specific WebElement.

public static String captureElementScreenshot(WebElement element, String name) {
    String path = "screenshots/" + name + "_" + getTimestamp() + ".png";
    File src = element.getScreenshotAs(OutputType.FILE);
    try {
        FileHandler.copy(src, new File(path));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return path;
}

Screenshot Naming Strategy:

  • <suite>_<testName>_<timestamp>.png

❌ Selenium - Screenshot on Test Failure (TestNG)

import org.testng.ITestListener;
import org.testng.ITestResult;

public class TestListener implements ITestListener {

    @Override
    public void onTestFailure(ITestResult result) {
        WebDriver driver = (WebDriver) result.getTestContext()
                .getAttribute("driver");

        ScreenshotUtil.captureBrowserScreenshot(
                driver,
                result.getMethod().getMethodName()
        );
    }
}

🔴 Selenium - Screenshot on Test Failure (JUnit 5)

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestWatcher;

public class ScreenshotWatcher implements TestWatcher {

    @Override
    public void testFailed(ExtensionContext context, Throwable cause) {
        WebDriver driver = DriverManager.getDriver();
        ScreenshotUtil.captureBrowserScreenshot(
                driver,
                context.getDisplayName()
        );
    }
}

🔗 Java - Base64 Screenshot (API / Test Reports)

Capture screenshots in Base64 format for API responses, Allure, Extent Reports, or JSON payloads without saving files on disk.

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public class ScreenshotUtil {

    /**
     * Capture screenshot as Base64 string
     */
    public static String captureBase64Screenshot(WebDriver driver) {
        if (driver == null) {
            System.err.println("WebDriver is null. Base64 screenshot skipped.");
            return null;
        }
        return ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.BASE64);
    }
}

When to use:

  • API-based test reports
  • Allure attachments
  • Extent Reports screenshots
  • Cloud executions (no local file access)

Example usage (Allure):

Allure.addAttachment(
    "Failure Screenshot",
    "image/png",
    new ByteArrayInputStream(
        Base64.getDecoder().decode(
            ScreenshotUtil.captureBase64Screenshot(driver)
        )
    ),
    ".png"
);

⚠️ Java - Failure Only Conditional Screenshots

Capture screenshots only when a test fails to reduce noise, execution time, and storage usage.

import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;

public class ScreenshotUtil {

    /**
     * Capture screenshot only on test failure
     */
    public static void captureOnFailure(
            ITestResult result,
            WebDriver driver
    ) {
        if (result.getStatus() == ITestResult.FAILURE && driver != null) {
            captureBrowserScreenshot(
                driver,
                result.getMethod().getMethodName()
            );
        }
    }
}

Recommended for:

  • Large regression suites
  • CI pipelines
  • Parallel executions
  • Clean reporting

TestNG Listener Usage

@Override
public void onTestFailure(ITestResult result) {
    WebDriver driver = (WebDriver) result
            .getTestContext()
            .getAttribute("driver");

    ScreenshotUtil.captureOnFailure(result, driver);
}

Benefits:

  • Faster execution
  • Less disk usage
  • Only meaningful screenshots stored

🔧 CI/CD - Screenshot Persistence Tips

  • Archive screenshots directory
  • Upload as pipeline artifacts
  • Attach to reports

🚨 Common Pitfalls

  • Do not overwrite screenshots
  • Ensure driver availability in listeners
  • Persist workspace in CI