Generating Reports in Selenium with TestNG Listeners (@Listeners)

 Generating Reports in Selenium with TestNG Listeners (@Listeners)

TestNG provides the IReporter listener interface to generate custom reports based on test execution. You can use it to create HTML, XML, or JSON reports.


1. Steps to Generate a Custom Report with @Listeners

A. Implement IReporter Interface

Create a custom report class by implementing IReporter.

B. Register the Listener

Register the listener in testng.xml or use the @Listeners annotation.


2. Creating a Custom Test Report Using IReporter

Step 1: Implement IReporter to Capture Test Execution Details

java

import org.testng.IReporter; import org.testng.ISuite; import org.testng.xml.XmlSuite; import java.io.FileWriter; import java.io.IOException; import java.util.List; public class CustomReportListener implements IReporter { @Override public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) { String reportFilePath = outputDirectory + "/CustomTestReport.html"; try (FileWriter writer = new FileWriter(reportFilePath)) { writer.write("<html><head><title>Test Execution Report</title></head><body>"); writer.write("<h1>Custom TestNG Execution Report</h1>"); for (ISuite suite : suites) { writer.write("<h2>Suite: " + suite.getName() + "</h2>"); suite.getResults().forEach((key, result) -> { writer.write("<h3>Test: " + result.getTestContext().getName() + "</h3>"); writer.write("<p>Passed Tests: " + result.getTestContext().getPassedTests().size() + "</p>"); writer.write("<p>Failed Tests: " + result.getTestContext().getFailedTests().size() + "</p>"); writer.write("<p>Skipped Tests: " + result.getTestContext().getSkippedTests().size() + "</p>"); }); } writer.write("</body></html>"); System.out.println("Custom Test Report Generated: " + reportFilePath); } catch (IOException e) { e.printStackTrace(); } } }

Step 2: Register Listener in testng.xml

To apply this listener to all test classes, add the following in testng.xml:

xml

<suite name="Test Suite"> <listeners> <listener class-name="CustomReportListener"/> </listeners> <test name="Sample Test"> <classes> <class name="TestExample"/> </classes> </test> </suite>

Step 3: Run Your TestNG Tests

When you run your TestNG tests, a custom HTML report will be generated in the test-output/CustomTestReport.html directory.


3. Enhancing the Report

You can improve the report by: ✅ Adding CSS styles for better formatting
Logging timestamps for test execution
Including detailed test case execution results
Generating JSON or XML reports

Would you like a detailed HTML report with screenshots on failure

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
https://otieu.com/4/9433883
https://otieu.com/4/9433883