
Selenium WebDriver has become a standard choice for automated web testing due to its cross-browser support and language flexibility. In test automation, screenshots serve as an essential debugging and reporting tool.
They provide a visual trail of application behavior during execution, making it easier to identify failures, UI issues, or inconsistencies. In fact, many QA teams consider screenshots indispensable for defect reporting and collaboration with developers.
Screenshots add value to test automation in several ways:
Before capturing screenshots, the environment must be correctly configured. The essential setup includes:
Sample Maven dependency for Selenium:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.12.0</version>
</dependency>
Selenium provides the TakesScreenshot interface to capture screenshots. The following are standard approaches:
Example code snippet:
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));
Screenshots extend beyond debugging, offering real-world benefits such as:
Selenium’s default capability captures only the visible viewport. For full-page screenshots:
Code example with AShot:
Screenshot fullPage = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000))
.takeScreenshot(driver);
ImageIO.write(fullPage.getImage(), "PNG", new File("fullPage.png"));
Capturing a single element is useful for debugging misaligned components or verifying specific UI states.
WebElement logo = driver.findElement(By.id("siteLogo"));
File elementShot = logo.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(elementShot, new File("logo.png"));
With TestNG, screenshots can be triggered automatically when a test fails. This can be achieved through listeners (ITestListener) that hook into the test lifecycle.
public void onTestFailure(ITestResult result) {
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("failure_" + result.getName() + ".png"));
}
When handling multiple screenshots in a single test execution:
TestNG listeners allow screenshot integration with minimal effort. By extending ITestListener, screenshots can be automatically added to reports. This reduces manual intervention while ensuring consistency across test runs.
When running tests in parallel, screenshots must correspond to the correct test thread. This requires thread-safe WebDriver management:
Appending the test method name and execution time to the screenshot filename ensures uniqueness and easy traceability.
String fileName = result.getMethod().getMethodName() + "_" + System.currentTimeMillis() + ".png";
Building a screenshot implementation in Selenium requires integrating multiple components so that screenshots are consistently captured, organized, and reported. Below is a step-by-step example in Java with TestNG.
Start by creating a base class to initialize and quit the WebDriver instance.
public class BaseTest {
protected WebDriver driver;
@BeforeMethod
public void setUp() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://example.com");
}
@AfterMethod
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
}
A utility class centralizes the logic for taking screenshots, making it reusable across tests.
public class ScreenshotUtil {
public static String captureScreenshot(WebDriver driver, String testName) {
String filePath = "screenshots/" + testName + "_" + System.currentTimeMillis() + ".png";
try {
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
}
Listeners allow screenshots to be taken automatically when a test fails.
public class ScreenshotListener implements ITestListener {
@Override
public void onTestFailure(ITestResult result) {
Object testClass = result.getInstance();
WebDriver driver = ((BaseTest) testClass).driver;
String screenshotPath = ScreenshotUtil.captureScreenshot(driver, result.getName());
System.out.println("Screenshot saved at: " + screenshotPath);
}
}
Register the listener in testng.xml:
<listeners>
<listener class-name="com.example.ScreenshotListener"/>
</listeners>
Screenshots should be stored in a clear directory hierarchy:
This produces clickable thumbnails in the TestNG HTML report, linking directly to the screenshot file.
Capturing screenshots is valuable, but without proper handling, they can quickly become unmanageable. The following practices improve efficiency:

Testing on local browsers is limited — real-world end-users access applications on a wide variety of devices, operating systems, and browser versions. Running screenshot-enabled Selenium tests on BrowserStack ensures comprehensive coverage.
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browserName", "Chrome");
caps.setCapability("browserVersion", "latest");
HashMap<String, Object> browserstackOptions = new HashMap<>();
browserstackOptions.put("os", "Windows");
browserstackOptions.put("osVersion", "11");
caps.setCapability("bstack:options", browserstackOptions);
WebDriver driver = new RemoteWebDriver(
new URL("https://hub-cloud.browserstack.com/wd/hub"), caps);
driver.get("https://example.com");
// Capture screenshot
ScreenshotUtil.captureScreenshot(driver, "BrowserStackTest");
driver.quit();
By integrating screenshot capture with BrowserStack’s real device cloud, teams ensure test reliability across real environments while benefiting from instant scalability and reduced maintenance overhead.
Screenshots in Selenium automation are more than just images; they are a critical part of debugging, reporting, and ensuring UI consistency across browsers. By adopting structured techniques, leveraging TestNG listeners, and managing WebDriver correctly in parallel runs, teams can optimize screenshot capture. Combined with BrowserStack’s real device cloud, these strategies enhance the reliability and scalability of automated testing.
Run Selenium Tests on Cloud
Get visual proof, steps to reproduce and technical logs with one click
Continue reading
Try Bird on your next bug - you’ll love it
“Game changer”
Julie, Head of QA
Try Bird later, from your desktop