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 + Javaimport 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();
}
}
}