Execution Listener in TestNG

We might need to do some set up before starting the execution of entire test suite or after finishing the execution of entire suite.

Execution listeners can be used in this scenario. With the help of listeners, we can invoke some methods right before and after suite execution.

First of all we need to create one class that implement IExecutionListener and then we need to pass the listener in Suite XML file.

Here is the sample class that implements the IExecutionListener interface. In this interface, we have 2 methods – onExecutionStart and onExecutionFinish. So we need to define these methods in class that implements IExecutionListener interface as depicted in below example.

package org.softpost;

import org.testng.IExecutionListener;

public class ExecutionListener implements IExecutionListener {

    public void onExecutionStart() {
       System.out.println("This method will be called right before starting the execution");
    }

    public void onExecutionFinish() {
        System.out.println("This method will be called right after execution is finished");
    }
}

Here is the sample TestNG.XML file. Please note that we have passed the listener class in <listeners> tag.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Suite">
    <listeners>
        <listener class-name="org.softpost.ExecutionListener" />
    </listeners>

    <test name="Tests">
        <classes>
            <class name="org.softpost.Class1" />
        </classes>
    </test>
</suite>

Here is the output of above code.

This method will be called right before starting the execution
[TestNG] Running:
C:\Users\Sagar\IdeaProjects\TestNG-Project\src\test\resources\testng.xml
Test1 from Class1
Test2 from Class1

===============================================
Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================

This method will be called right after execution is finished

You may also like...