TestNG | Custom Listener using ISuiteListener

We have a listener for the suite called ISuiteListener. This listener has two methods, onStart and onFinish. Method onStart is invoked before TestNG starts running the suite and onFinish is invoked after TestNG has run the suite.

Before TestNG picks up your suite for execution, it first makes a call to the onStart() method and runs whatever has been scripted in this method. In a similar way, it again makes a call to the onFinish() method after a suite has been run. This does not affect any tags and methods. It runs on suite start and ends, before and after any tags and methods are reached. 

The listener is called for each suite. If the parent suite contains child suites, the child suites are run before running the parent suite. This is done so that the results for parent suite can reflect the combined results of the child suites.

In the following test configuration, we have a parent suite containing child suites.

Copy
<?xml version="1.0" encoding="UTF-8"?>
<suite name="SuiteListener">    
  <listeners>        
     <listener class-name="listenerspackage.TestNG_ListenersSuite" />
  </listeners> 
 <suite-files>
  <suite-file path="./childSuite.xml"/>  
 </suite-files>
</suite>

As for each other Listener type, you need to create a class and implement the Listener Interface. Then, in Eclipse, hover over the class name and select the option to add unimplemented methods. This will automatically add both of the listener methods, as follow:

Copy
package listenerspackage;

import org.testng.ISuite;
import org.testng.ISuiteListener;

public class CustomListener3 implements ISuiteListener {

    @Override
    public void onStart(ISuite suite) {
        // When <suite> tag starts
        System.out.println("onStart: before suite starts");
    }

    @Override
    public void onFinish(ISuite suite) {
        // When <suite> tag completes
        System.out.println("onFinish: after suite completes");
    }
}

Because this listener affects only the suite level, you have to implement it inside the testng.xml file. You cannot use the test class approach here.

Copy
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Listeners TestSuite">
  <listeners>    
     <listener class-name="listenerspackage.TestNG_ListenersSuite"></listener>
  </listeners>
  <test name="Application Test 1">
    <classes>
      <class name="testclasses.TestNG_ListenersTest1"></class>
    </classes></test>
  <test name="Application Test 2">    
    <classes>
      <class name="testclasses.TestNG_ListenersTest2"></class>
    </classes>
  </test>
</suite>