πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 56 of 100
Framework Design
Intermediate

Capturing High-Quality Screenshots on Failure

πŸ“ΈScenario Overview

Capturing High-Quality Screenshots on Failure

Key Takeaways & Cheat Sheet

  • βœ“Cast the WebDriver instance directly to TakesScreenshot interface
  • βœ“Invoke getScreenshotAs(OutputType.FILE) to grab the screen state
  • βœ“Save files dynamically using unique timestamps or test method names
  • βœ“Integrate screenshot capturing with TestNG ITestListener onTestFailure

Short Direct Answer

To capture screenshots on failure, cast your WebDriver instance to the `TakesScreenshot` interface, call `getScreenshotAs(OutputType.FILE)`, and write the returned file object to a persistent directory. The most professional implementation binds this capture utility inside a custom TestNG `ITestListener`'s `onTestFailure` method so screenshots are captured automatically only when a test fails.

⚠️ Senior Warning (Red Flag)

Never call screenshot capture inside individual try-catch blocks in every test. This pollutes your test logic with boilerplate code. Centralize it within a global test listener instead.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Saving screenshots using the test method name combined with a timestamp prevents assets from overwriting each other across parallel executions.

SeleniumAutomation.java
Selenium 4 + Java
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;

// βœ… Automated Test Failure Listener Capture
public class TestListener extends TestListenerAdapter {
    @Override
    public void onTestFailure(ITestResult result) {
        // Retrieve webdriver instance from the active test class
        Object currentClass = result.getInstance();
        WebDriver driver = ((BaseTest) currentClass).getDriver();
        
        // Capture screenshot
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        String destPath = System.getProperty("user.dir") + "/target/screenshots/" 
            + result.getName() + "_" + System.currentTimeMillis() + ".png";
        
        try {
            FileUtils.copyFile(srcFile, new File(destPath));
            System.out.println("Screenshot saved to: " + destPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}