Can Selenium Take a Screenshot on Test Failure with JUnit?
Capture Selenium screenshots automatically when JUnit tests fail. See working JUnit 4 and 5 hooks, artifact handling, Selenide options, and troubleshooting.

Yes. Selenium can capture the browser state when a JUnit test fails. Use Selenium’s TakesScreenshot interface to capture the image, and use JUnit’s failure lifecycle callback to decide when to call it. In JUnit 4, use a TestWatcher rule; in JUnit 5, implement an extension callback such as AfterTestExecutionCallback. Save the file before your teardown quits the WebDriver, create the destination directory, and treat capture as best effort so a screenshot error does not replace the original test failure.
The key division of work is simple: WebDriver talks to the browser, while JUnit runs the test and exposes lifecycle callbacks. Selenium’s screenshot method is getScreenshotAs(OutputType.FILE); it can throw WebDriverException if capture fails. See the Selenium TakesScreenshot API and the JUnit 5 user guide.
1. Choose a hook that runs before WebDriver teardown
A screenshot is useful only if the browser session still exists when the callback runs. The test framework invokes setup, the test, and teardown according to their respective lifecycle rules. Put capture in the failure callback and keep driver shutdown after that callback. If an @AfterEach method or test rule quits the driver first, the failure hook may see a dead session.
Use the implementation that matches the test framework already running your suite:
| Suite | Failure hook | Best fit |
|---|---|---|
| JUnit 4 | TestWatcher.failed |
Existing JUnit 4 tests and rules |
| JUnit 5 / Jupiter | AfterTestExecutionCallback |
Tests using Jupiter extensions |
| Selenide with its static driver | ScreenShooterExtension |
Selenide-managed static WebDriver |
For either custom hook, decide where screenshots belong, ensure that directory is created, and make filenames unique when tests can run concurrently or repeat with the same method name.
2. JUnit 5: capture after a failed test method
JUnit Jupiter extensions can be registered with @ExtendWith or programmatically using @RegisterExtension. An AfterTestExecutionCallback runs after the test method, allowing the extension to inspect its outcome. The example below assumes the suite’s DriverHolder.current() returns the WebDriver for the current test thread. Replace it with your own driver provider or dependency injection. The holder must still return the live driver at callback time.

import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public final class ScreenshotOnFailure
implements AfterTestExecutionCallback {
@Override
public void afterTestExecution(ExtensionContext context) {
if (context.getExecutionException().isEmpty()) {
return;
}
WebDriver driver = DriverHolder.current();
if (driver == null) {
return;
}
String className = context.getRequiredTestClass().getSimpleName();
String methodName = context.getRequiredTestMethod().getName();
Path destination = Paths.get("target", "screenshots",
className + "_" + methodName + ".png");
try {
Files.createDirectories(destination.getParent());
File source = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
Files.copy(source.toPath(), destination,
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException | RuntimeException captureError) {
// Log captureError. Do not replace the original test failure.
}
}
}
Register the extension on a class or method:
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(ScreenshotOnFailure.class)
class CheckoutTest {
// Create the driver in setup and quit it after the extension callback.
}
The code imports only Selenium and JUnit APIs. The DriverHolder is deliberately application-specific: a global static variable is not safe if multiple tests execute in parallel. Prefer a thread-local or framework-managed driver association, and make sure the same association is visible to the extension. If the test is parameterized or repeated, include a unique invocation identifier in the destination name to avoid overwriting earlier captures.
The callback checks the test method’s execution exception. It does not necessarily capture failures that happen in setup, teardown, or other lifecycle callbacks, since those are distinct from the test method execution. If those failures matter, extend the design to observe the relevant lifecycle callbacks or use a JUnit extension that tracks the test’s full outcome. Do not assume a method-only callback reports every possible failure in the test lifecycle.
3. JUnit 4: use a TestWatcher rule
JUnit 4 provides TestWatcher.failed(Throwable, Description). The rule below captures on failure and uses the test class and method in the filename. It uses Apache Commons IO for a concise file copy; add commons-io if it is not already available, or replace FileUtils.copyFile with Files.copy.
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import java.io.File;
import java.io.IOException;
public class CheckoutTest {
private WebDriver driver;
@Rule
public TestRule screenshotOnFailure = new TestWatcher() {
@Override
protected void failed(Throwable error, Description description) {
if (driver == null) {
return;
}
try {
File source = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
File destination = new File("target/screenshots/"
+ description.getClassName() + "_"
+ description.getMethodName() + ".png");
FileUtils.forceMkdirParent(destination);
FileUtils.copyFile(source, destination);
} catch (WebDriverException | IOException captureError) {
// Log captureError and preserve the test's original failure.
}
}
};
}
If your Commons IO version does not provide forceMkdirParent, create the parent directory with destination.getParentFile().mkdirs() and verify the result, or use Java NIO. The rule must have access to the same driver instance used by the test. Review the order of rules and teardown carefully; if the driver is quit before failed runs, the capture will fail.
4. Use Selenide’s extension when its driver model fits
For a Selenide suite that uses Selenide’s static WebDriver, its JUnit 5 extension can take screenshots automatically when tests fail:
import com.codeborne.selenide.junit5.ScreenShooterExtension;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(ScreenShooterExtension.class)
class MySelenideTest {
// Selenide test methods
}
Selenide documents its reports folder configuration and describes the extension as handling errors beyond Selenide assertion failures. Its current Javadoc states an important restriction: ScreenShooterExtension works with Selenide’s static WebDriver. It does not capture from a driver created directly with new SelenideDriver(). For direct Selenium, or for separately managed Selenide drivers, use a custom extension that receives the correct driver. See the Selenide screenshot documentation and ScreenShooterExtension Javadoc.
5. Store and publish screenshots as build artifacts
Selenium returns a temporary screenshot file when you request OutputType.FILE. Copy it immediately to a stable path in the project’s build output, such as target/screenshots. The destination and CI publishing step belong to your build configuration; Selenium does not automatically attach the file to a test report.
- Create the destination directory before copying.
- Use a filename with class, method, and—when needed—test invocation or worker identity.
- Copy the file before the browser quits or the temporary source is removed.
- Configure your CI system to retain the screenshot directory when a job fails.
- Keep the original test exception as the primary failure; report screenshot capture errors as supplementary diagnostics.
For Java NIO in either framework, the core operations are:
Path destination = Paths.get("target", "screenshots", "failure.png");
Files.createDirectories(destination.getParent());
File source = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Files.copy(source.toPath(), destination,
StandardCopyOption.REPLACE_EXISTING);
Use OutputType.BYTES if your report integration accepts byte arrays or you want to pass data directly to another API; use OutputType.BASE64 if its consumer explicitly expects Base64. A file is convenient for build artifacts. Whichever output type you choose, the browser still must support screenshot capture and remain available until the command completes.
6. Options, boundaries, and edge cases
Visible viewport versus full page
getScreenshotAs captures according to the WebDriver implementation and specification. Do not assume that a standard driver screenshot always captures an entire long page: driver and browser behavior can differ. Selenium’s API documents screenshot capture for a driver or HTML element and notes best-effort behavior for non-conformant implementations. If you need a specific full-page result, check the browser and driver capabilities you use rather than treating viewport capture as full-page capture.
Parallel runs and repeated methods
Two workers can fail the same test method at once, and parameterized tests can invoke one method many times. A path made only from class and method overwrites earlier evidence. Add a unique invocation component, such as a sanitized display name plus a UUID, and avoid sharing a mutable driver across tests. Also ensure the callback retrieves the driver for the failing test rather than whichever driver was most recently assigned to a static field.
Failures before the browser starts
If setup fails before creating the driver, there is no page to capture. A null check is appropriate. If navigation fails after browser creation, capture may still work and can show the last rendered state, but the WebDriver command can also fail if the session has already crashed or disconnected.
Remote WebDriver and containers
The screenshot request goes through the active WebDriver session. In a remote setup, capture depends on that session and its remote end being reachable. Copy the returned file on the test runner where the Selenium client receives it, and publish that local artifact from the runner. A disconnected session or expired remote session can make the capture fail; preserve the test failure and record the screenshot error for diagnosis.
Multiple windows, frames, and sensitive pages
The screenshot reflects the browser’s current context. If the test switched windows or frames before failing, that context influences the captured view. Consider returning to the relevant window before assertions if that is part of the scenario. Screenshots may contain account data, tokens, personal information, or customer records. Restrict artifact access and retention according to your team’s data handling rules; avoid capturing secrets in test pages.
7. Troubleshooting common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| No screenshot file appears | The failure hook was not registered, or the destination directory does not exist. | Confirm the JUnit rule or extension is active, create parent directories, and check the configured artifact path. |
WebDriverException during capture |
The session ended, disconnected, crashed, or does not support screenshots. | Run capture before quit(), verify the session is alive, and log capture errors without masking the assertion. |
| NullPointerException in the hook | Setup failed before assigning the driver, or the extension cannot access the test’s driver. | Guard against null and connect the callback to the test-scoped driver provider. |
| FileNotFoundException or copy failure | Parent folder is absent, permissions deny writing, or temporary source file is unavailable. | Create the directory, use a writable build path, and copy the returned file immediately. |
| Earlier screenshots disappear | Different runs use the same class-and-method filename. | Add an invocation ID or timestamp and keep paths unique across workers. |
| JUnit 5 callback does not run for setup error | AfterTestExecutionCallback observes test execution outcome, not necessarily every lifecycle failure. |
Track the lifecycle callback where the error can occur and capture while the driver remains alive. |
| Selenide extension produces no image | The test uses a non-static SelenideDriver instance. |
Use Selenide’s static driver as required by the extension or write a custom hook for that instance. |
| Screenshot is of the wrong tab | The current WebDriver window differs from the expected one. | Capture the intended window context or record the active handle as diagnostic metadata. |
8. Performance, reliability, and cost
Failure-only capture adds work only when a test fails, which keeps the normal passing path lightweight. The browser must process the screenshot command and the test runner must write the artifact, so a large image or slow remote session can increase the time spent reporting a failure. Avoid taking screenshots on every passing test unless that evidence serves a specific debugging purpose.

Screenshot capture is diagnostic best effort, not a replacement for the test result. Catch capture and file errors, log them, and retain the original assertion or exception as the primary failure. CI should collect artifacts even when the test task exits unsuccessfully; otherwise a successfully captured file can still be discarded with the job workspace. There is no separate Selenium screenshot API charge in the described local WebDriver pattern, though browser infrastructure and CI storage may have their own costs.
Or skip the browser setup
If you need a screenshot of a public page rather than the exact browser state created by a failing test, ScreenshotNeo provides a one-request website screenshot API and MCP server. Selenium remains useful when the failing state depends on your test’s login, data, or interaction history. ScreenshotNeo is an option for capturing a URL without managing a browser session.
See the ScreenshotNeo API docs. One GET request returns an image or PDF; here is the API call in cURL:
curl -G "https://api.screenshotneo.com/v1/shot" \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://stripe.com \
-o shot.webp
Python:
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
Node.js:
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
const bytes = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', bytes));
- Cookie banners, newsletter popups, and chat widgets are removed before the shot; each cleanup step can be turned off.
- Bot checks, blank pages, failed loads, timeouts, and cache hits are never billed; response headers report the page verdict and billing status.
- An MCP server gives AI agents tools to take screenshots, get page information, and capture PDFs.
- 1,000 screenshots a month are free with no card; paid plans start at $5 for 3,000.
Create a free ScreenshotNeo account to get 1,000 screenshots each month with no card.
9. FAQ
Can I capture the browser console or network log in the same screenshot?
No. A screenshot records rendered pixels. Capture console messages, network events, and browser logs through separate WebDriver or browser tooling and attach them as separate artifacts.
Does JUnit itself take screenshots?
No. JUnit provides rules and extension callbacks; Selenium performs the browser capture. Your code chooses the file path and your build system retains the artifact.
Will this work with any WebDriver implementation?
It works when the active implementation supports Selenium’s screenshot interface. Unsupported implementations can throw an exception, so keep capture failure handling separate from the test failure.
Should screenshots be committed to source control?
Usually they belong in build artifacts or a test report, not in source control. Retain them long enough to investigate failures and restrict access if pages contain sensitive data.


