Listeners

A listener is defined as an interface through which we can change the default TestNG’s behavior. As the name suggests Listeners “listen” to the given event defined in the selenium script and behave accordingly. This is implemented in script with the help of Listener interface. It supports in customizing the TestNG reports or logs. There are many types of TestNG listeners available.

Most common TestNG Listeners

  • ITestListener
  • ISuiteListener
  • IReporter
  • IMethodInterceptor
  • IExecutionListener
  • IHookable
  • IConfigurable
  • IConfigurationListener

TestNG Listeners interfaces are used in selenium to generate logs or customize the Testing reports.

Now we will discuss ITestListener. ITestListener has the following methods:

  • onStart- This method is called when any Test method starts.
  • onTestSuccess- This method is called on the success of any Test.
  • onTestFailure- This method is called on the failure of any Test.
  • onTestSkipped- This method is called on skipped of any Test.
  • onTestFailedButWithinSuccessPercentage- This method is called each time Test fails but is within success percentage.
  • onFinish- This method is called after all Tests are executed.

Let us see how to implement TestNG Listeners.

Steps:

Step 1: Create a class ListenerTest and implement this class with ITestListener interface.
In this interface, we have few unimplemented methods which we need to implement in our class. Also, we can implement a few methods and can see the changes, for example, onTestSuccess, onTestFailure methods.

Let us see an example:

package testFramework;

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

public class ListenerTest implements ITestListener {

  @Override
  public void onTestStart(ITestResult result) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onTestSuccess(ITestResult result) {
    System.out.println("Success test case name is:" + result.getName());

  }

  @Override
  public void onTestFailure(ITestResult result) {
    System.out.println("Failure test case name is:" + result.getName());

  }

  @Override
  public void onTestSkipped(ITestResult result) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onStart(ITestContext context) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onFinish(ITestContext context) {
    // TODO Auto-generated method stub

  }
}