👀 Listeners Interface In TestNG

Execute code on a particular condition.

Fareena Imran
3 min readFeb 21, 2022

▶️ What are TestNG listeners ❔

TestNG has some intelligent mechanism with the help of listeners that redirect your execution toward one block of code 📟 when your test case got failed.

The listener listens to our execution results, when it listen that something is failed then it invokes one particular method, and again it will keep on listening 👂 and when it listens to that something is successful then it invokes one another method. So you can write whatever you need to perform in that particular method.

▶️ When To Use ❔

If you’re working on appium or selenium and suddenly at one particular page your test case got failed ❌ and you have to take screenshots on every test case failure then you can use TestNG listeners.

✔️ For Example:

When you work on Rest API’s whenever you see the response code is not 200 then the test script will fail. So, at that time we need to redirect execution to the specific block of code where we will write the code to perform specific actions on failure, it's either to take a screenshot of the screen where the test case got failed or print the logs, etc.

▶️ How To Implement Listeners ❔

ITestListener interface is used to implement the listeners in TestNG which has all the methods for TestNG listeners. Follow the steps for implementing listeners in your automation code 👇

✔️ Steps

#1) Create a Java Class

First, create a java class name as “MyClass”. Now use the ITestListener interface with the Java class by using the “implements” keyword like in the example below 👇

You will get an error under the word “ITestListener”, hover on it then click on “Import ‘ITestListener’ (org. testng)”, then the error will be removed.

#2 ) Add ITestListener Methods

Right-click on the java file “MyClass” → go to “Source” → then “Override/ Implements Methods..” then you will get a wizard, select the check box for “ITestListener” → click on “Ok”. You will see all the methods in your java file like this 👇

#3) Add Listener Class in XML file

Code

Use the code on your side and see the result of test cases with the listener.

Now Run the XML file and see the output 💻 In this way you can write your own code depending on the action you want to perform. I just used two listener methods “onTestFailuer” and “onTestSuccess”.

Follow my articles to learn more about the TestNG framework.

Best of Luck 👍

--

--