Search⌘ K
AI Features

How to Take Screenshots and Exceptions

Explore how to enhance your Selenium test automation by using TestNG listeners to capture screenshots and exception details. This lesson teaches how to avoid code duplication, improve debugging, and automatically log test statuses through efficient listener implementation during test execution.

A good test automation solution includes more than just test and page object classes. It should have support for collecting debugging information if any test fails. This means taking screenshots, collecting exceptions and stack traces, and saving them to a log file.

Do not take screenshots/logs in test methods

It is a bad idea to take screenshots and collect exceptions/stack traces with try/catch statements in the test method as it leads to code duplication:

Java
@Test(groups = "Medium")
public void any_Page_Has_Results_Test()
{
try
{
HomePage homePage = openHomePage();
ResultsPage resultsPage = homePage.searchFor(KEYWORD);
Assert.assertEquals(resultsPage.resultsPerPage(), "1 to 10");
ResultsPage resultsPage3 = resultsPage.goToPage(3);
Assert.assertEquals(resultsPage3.resultsPerPage(), "21 to 30");
ResultsPage resultsPage5 = resultsPage3.goToPage(5);
Assert.assertEquals(resultsPage5.resultsPerPage(), "41 to 50");
}
catch (Exception e)
{
//take screenshot
//log exception and stack trace
}
}

Do not take

...