</>

Technology

TestNG

Difficulty

Intermediate

Interview Question

What is the use of TestNG Listeners?

TestNG Listeners intercept test events (pass, fail, skip) to perform custom actions like logging and reporting.

Answer

TestNG Listeners

Listeners in TestNG allow you to respond to test events — like test start, success, failure, or skip — and perform custom actions such as logging, screenshot capture on failure, or custom reporting.

How Listeners work:

  1. TestNG fires events when tests run (onTestStart, onTestSuccess, onTestFailure, etc.)
  2. You implement the ITestListener interface to hook into these events
  3. Your custom code runs automatically at each event

Key Listener interfaces:

  • ITestListener – Handles test-level events (most common)
  • ISuiteListener – Handles suite-level events (onStart, onFinish)
  • IReporter – Generates custom reports after suite execution

Implementing ITestListener:

Java
package testnglisteners;

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

public class Mylisteners implements ITestListener {

    @Override
    public void onTestStart(ITestResult result) {
        System.out.println("Test started: " + result.getName());
    }

    @Override
    public void onTestSuccess(ITestResult result) {
        System.out.println("Test passed: " + result.getName());
    }

    @Override
    public void onTestFailure(ITestResult result) {
        System.out.println("Test failed: " + result.getName());
        // Take screenshot on failure here
    }

    @Override
    public void onTestSkipped(ITestResult result) {
        System.out.println("Test skipped: " + result.getName());
    }

    @Override
    public void onTestFailedButWithinSuccessPercentage(ITestResult result) { }

    @Override
    public void onStart(ITestContext context) { }

    @Override
    public void onFinish(ITestContext context) { }
}

Practical use — screenshot on failure:

Java
@Override
public void onTestFailure(ITestResult result) {
    TakesScreenshot ts = (TakesScreenshot) driver;
    File src = ts.getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(src, new File("screenshots/" + result.getName() + ".png"));
}

Register listener in testng.xml:

XML
<suite name="MySuite">
  <listeners>
    <listener class-name="testnglisteners.Mylisteners" />
  </listeners>
  <test name="LoginTest">
    <classes>
      <class name="tests.LoginTest" />
    </classes>
  </test>
</suite>

Key points:

  1. TestNG listeners perform actions when test events are triggered
  2. Most commonly used for configuring reports and logging
  3. ITestListener and TestListenerAdapter are the most widely used
  4. Methods: onTestSuccess, onTestFailure, onTestSkipped, onStart, onFinish
  5. You must implement the interface in a listener class of your own

Follow AutomateQA

Related Topics