Answer
Auto-Screenshot on Test Failure
Capturing screenshots on failure helps identify exactly what the browser showed when the test broke — crucial for debugging in CI/CD.
Method 1 — TestNG @AfterMethod (Simple)
Java
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;
import org.apache.commons.io.FileUtils;
import org.testng.ITestResult;
import java.io.File;
@AfterMethod
public void captureScreenshotOnFailure(ITestResult result) throws Exception {
if (result.getStatus() == ITestResult.FAILURE) {
TakesScreenshot ts = (TakesScreenshot) driver;
File src = ts.getScreenshotAs(OutputType.FILE);
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String path = "screenshots/" + result.getName() + "_" + timestamp + ".png";
FileUtils.copyFile(src, new File(path));
System.out.println("Screenshot saved: " + path);
}
}
Method 2 — TestNG ITestListener (Framework-Level)
Java
public class ScreenshotListener implements ITestListener {
@Override
public void onTestFailure(ITestResult result) {
WebDriver driver = DriverManager.getDriver(); // get driver from ThreadLocal
TakesScreenshot ts = (TakesScreenshot) driver;
byte[] screenshot = ts.getScreenshotAs(OutputType.BYTES);
// Attach to Extent Report
ExtentReportManager.getTest().addScreenCaptureFromBase64String(
Base64.getEncoder().encodeToString(screenshot),
"Failure Screenshot"
);
}
}
Register the listener in testng.xml:
XML
<listeners>
<listener class-name="listeners.ScreenshotListener"/>
</listeners>
Method 3 — Save with Timestamp
Java
public static String captureScreenshot(WebDriver driver, String testName) {
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String screenshotPath = "test-output/screenshots/" + testName + "_" + timestamp + ".png";
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File dest = new File(screenshotPath);
try {
FileUtils.copyFile(src, dest);
} catch (IOException e) {
e.printStackTrace();
}
return screenshotPath;
}
Best Practices
- ✓Always name screenshots with test name + timestamp to avoid overwrites
- ✓Save to a dedicated
screenshots/folder tracked by CI artifacts - ✓Attach screenshots to ExtentReports or Allure for visual reports
- ✓Use Base64 encoding to embed screenshots directly in HTML reports
- ✓Take screenshot before
driver.quit()in @AfterMethod
