We can capture screenshots automatically whenever a test fails in Selenium by implementing the ITestListener interface. The onTestFailure() method in the listener class gets triggered whenever a test fails, and inside it we can capture and save the screenshot.
In the following example, I’ve created a listener class to handle screenshots and a test class that purposefully fails using Assert.assertEquals() on the page title. This helps us verify that the screenshot mechanism works as expected. Here test class is calling listener class ScreenshotListener to take screen shot using onTestFailure method.
✅Example Test for handling failed test case:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.*;
@Listeners(ScreenshotListener .class)
public class GoogleTest {
WebDriver driver;
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
driver.manage().window().maximize();
ScreenshotListener.setDriver(driver); // pass driver to listener
}
@Test
public void testGoogleTitle() {
driver.get("https://www.google.com");
// ❌ Intentional fail (Google title is "Google", not "Yahoo")
Assert.assertEquals(driver.getTitle(), "Yahoo");
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}
Below is an example of a TestNG listener class that handles test failures by capturing a screenshot inside the onTestFailure() method:
✅ScreenshotListener class:
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class ScreenshotListener implements ITestListener {
private WebDriver driver;
public ScreenshotListener(WebDriver driver) {
this.driver = driver;
}
@Override
public void onTestFailure(ITestResult result) {
TakesScreenshot ts = (TakesScreenshot) driver;
File src = ts.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(src, new File("screenshots/" + result.getName() + ".png"));
System.out.println("Screenshot taken for failed test: " + result.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
}