Home » TestNG Listeners

TestNG Listeners

TestNG provides the @Listeners annotation which listens to every event that occurs in a selenium code. Listeners are activated either before the test or after the test case. It is an interface that modifies the TestNG behavior. For example, when you are running a test case either through selenium or appium and suddenly a test case fails. We need a screenshot of the test case that has been failed, to achieve such scenario, TestNG provides a mechanism, i.e., Listeners. When the test case failure occurs, then it is redirected to the new block written for the screenshot.

Listeners are implemented by the ITestListener interface. An ITestListener interface has the following methods:

TestNG Listeners

onTestStart(): An onTestStart() is invoked only when any test method gets started.

onTestSuccess(): An onTestSuccess() method is executed on the success of a test method.

onTestFailure(): An onTestFailure() method is invoked when test method fails.

onTestSkipped(): An onTestSkipped() run only when any test method has been skipped.

onTestFailedButWithinSuccessPercentage(): This method is invoked each time when the test method fails but within success percentage.

onStart(): An onStart() method is executed on the start of any test method.

onFinish(): An onFinish() is invoked when any test case finishes its execution.

How to create the TestNG Listeners

We can create the TestNG Listeners in two ways. First we can use the @Listeners annotation within the class and second way to use the within the suite.

First case: First, we will create the listeners within the class.

Step 1: Open the Eclipse.

Step 2: We create a simple project.

In the above code, we create two test cases, i.e., sum() and testtofail().

Listener.java

When sum() test case has been passed, then TestNG calls the onTestSuccess() listener. When testtofail() test case has been failed, then TestNG calls the onTestFailure() listener.

Step 3: Now, we create the testng.xml file.

Step 4: Run the testng.xml file. Right click on the testng.xml file and move the cursor down to Run As and then click on the 1 TestNG Suite.

TestNG Listeners

The above output shows that sum() test case has been passed and testtofail() testcase has been failed.

Second case: Now we create the listeners by using testng.xml file.

Step 1: Open the Eclipse.

Step 2: We will create two java projects. One java project is containing the test cases and another project is containing listeners.

Testcases.java

Listener.java

Step 3: Now, we create the testng.xml file.

testng.xml

Step 4: Run the testng.xml file.

Output

TestNG Listeners

Note: When listeners are added to multiple classes then it could be an error prone. If listeners are implemented through the testng.xml file, then they are applied to all the classes.


Next Topic#

You may also like