EDUCBA

EDUCBA

MENUMENU
  • Blog
  • Free Courses
  • All Courses
  • All in One Bundle
  • Login
Home Software Development Software Development Tutorials Software Testing Tutorial Listeners in TestNG

Listeners in TestNG

By Yashi GoyalYashi Goyal

listeners in testng

Introduction to Listeners in TestNG

Before understanding Listeners in TestNG first, we will study Listeners and TestNG separately. We wish to modify TestNG behavior in our application, and Interfaces can do this. These interfaces which help the user to do so are known as Listeners. As the name suggests, ‘Listeners’ primary task is to listen to an event defined and react according to that. The main purpose for which the programmers use listeners is to create logs and create the custom reports according to the specific scenario defined.

Types of Listeners in TestNG

There are various types of Listeners in TestNG, and each listener serves its different purpose. Some of them are mentioned below:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  1. IConfigurable
  2. IAnnotationTransformer
  3. IHookable
  4. IReporter
  5. ISuiteListener

Methods of Listeners in TestNG

Though there are many listeners available in TestNG and each listener has specific methods that are overridden. Let’s discuss the 2 most popular listeners and the methods which they override:

1. ITestListener

ITestListener is one of the most commonly used listeners in Selenium Webdriver. The programmer simply needs to implement the ITestListener interface and override all the interface methods to use it. It makes the call before and after every test present in the suite. There are several methods in it which are mentioned below:

  • onStart: This is the first and foremost method that is called after the test class is instantiated. It can also be used to retrieve the directory from which the test is running.
  • onFinish: This is the last method to be called after all the overridden methods are done.
  • onTestStart(ITestResult result): This method is called each time before any new test method. It indicates that a required test method is started.
  • onTestFailure(ITestResult result): This method is called when any test method fails as it indicates the test’s failures. We can perform certain tasks on test failure, like taking the screenshot when a particular test fails, in order to get more deep insight into failure.
  • onTestSkipped(ITestResult result): This method is called when any test method is skipped for execution.
  • onTestSuccess(ITestResult result): This method is called when a particular test method is successfully executed. The programmer can perform any desired operation on test method success by writing code inside this method.
  • onTestFailedButWithinSuccessPercentage(ITestResult result): This method is called when any test method is failed with some success percentage. For example, it represents the case if any test method is executed 10 times and failed 5 times. It takes 2 parameters, i.e. successPercentage and invocationCount. For the above case, successPercentage would be 50, and the invocationCount would be 10.

2. ISuiteListener

Unlike the ITestListener, which is implemented after every test method, ISuiteListener is implemented at the Suite level. It has two methods that are overridden:

  • onStart: This method is implemented before the test suite’s invocation, which means all the code written inside it is run before the start of any suite.
  • onFinish: This method is implemented after the test suite’s invocation, which means all the code written inside it is run after the whole test suite is run.

How to Create Listeners in TestNG?

There are basically 2 ways of creating Listeners in TestNG:

1. We can use the @Listeners interface within the class.

Step 1: The first and foremost step is to create a class for Listener, which is implementing ITestListener and overriding all its methods explained above.

Class: TestListener.java

Code:

package Demo;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class TestListener implements ITestListener
{
@Override
public void onTestStart(ITestResult res)
{
System.out.println("Started test case is "+ res.getName());
}
@Override
public void onStart(ITestContext res)
{
}
@Override
public void onFinish(ITestContext res)
{
}
// Run when the test case passed successfully
@Override
public void onTestSuccess(ITestResult res)
{
System.out.println("Test case passed is "+res.getName());
}
// Run when the test case fails
@Override
public void onTestFailure(ITestResult res)
{
System.out.println("Test case failed is "+res.getName());
}
// Run when test case pass with some failures
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult res)
{
System.out.println("Test case passed with failure is "+res.getName());
}
// Run when the test case is skipped
@Override
public void onTestSkipped(ITestResult res)
{
System.out.println("Test case skipped is :"+res.getName());
}
}

Step 2: Next, we need to implement the above Listener in the normal Java Program of login in an application having the @test methods using @Listeners annotation.

Class: Testing.java

Code:

package Demo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners(Demo.TestListener.class)
public class Testing
{
String driverPath =
"C:\\Users\\username\\Downloads\\Compressed\\geckodriver.exe";
public WebDriver driver;
@BeforeMethod
public void startBrowser() {
System.setProperty("webdriver.gecko.driver",driverPath);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette",true);
driver= new FirefoxDriver();
}
// Test case to login an application which will pass .
@Test
public void LoginMethod()
{
driver.get("http://testing-ground.scraping.pro/login"); driver.findElement(By.id("usr")).sendKeys("admin");
driver.findElement(By.id("pwd")).sendKeys("123");
driver.findElement(By.xpath("//*[@id=\"case_login\"]/form/input[3]")).
click();
}
// Test case for failure in order to check the working of listener.
@Test
public void FailMethod()
{
System.out.println("Forcefully making the method to fail");
Assert.assertTrue(false);
}
}

Step 3: Now, we can add an entry of the class in the XML file like the one given below:

Code:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="ListenerTest">
<classes>
<class name="Demo.Testing.class"></class>
</classes>
</test>
</suite> <!-- Suite -->

Output:

output1 listener testng

2. We can use add Listeners in the XML file directly.

Though the above approach to adding the @listeners in specific classwork in a suite with so many classes, it is not considered a nice approach to add the listener to each class. Instead, we can create the entry of Listeners and classes in the XML file.

Step 1: Creating a Listener class in Java, implementing the ITestListener and overriding its methods similar to the one mentioned above.

Class: TestListener.java

Code:

package Demo;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class TestListener implements ITestListener
{
@Override
public void onTestStart(ITestResult res)
{
System.out.println("Started test case is "+ res.getName());
}
@Override
public void onStart(ITestContext res)
{
}
@Override
public void onFinish(ITestContext res)
{
}
// Run when the test case passed successfully
@Override
public void onTestSuccess(ITestResult res)
{
System.out.println("Test case passed is "+res.getName());
}
// Run when the test case fails
@Override
public void onTestFailure(ITestResult res)
{
System.out.println("Test case failed is "+res.getName());
}
// Run when test case pass with some failures
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult res)
{
System.out.println("Test case passed with failure is "+res.getName());
}
// Run when the test case is skipped
@Override
public void onTestSkipped(ITestResult res)
{
System.out.println("Test case skipped is :"+res.getName());
}
}

Step 2: Next, we need to create a normal Java Program of login in an application having all the @test methods, and there is no need to use @Listeners annotation.

Class: Testing.java

Code:

package Demo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
public class Testing
{
String driverPath = "C:\\Users\\username\\Downloads\\Compressed\\geckodriver.exe";
public WebDriver driver;
@BeforeMethod
public void startBrowser() {
System.setProperty("webdriver.gecko.driver",driverPath);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette",true);
driver= new FirefoxDriver();
}
// Test case to login an application which will pass.
@Test
public void LoginMethod()
{
driver.get("http://testing-ground.scraping.pro/login"); driver.findElement(By.id("usr")).sendKeys("admin");
driver.findElement(By.id("pwd")).sendKeys("123");
driver.findElement(By.xpath("//*[@id=\"case_login\"]/form/input[3]")).
click();
}
// Test case for failure in order to check the working of listener.
@Test
public void FailMethod()
{
System.out.println("Forcefully making the method to fail");
Assert.assertTrue(false);
}
}

Step 3: Now, we can add an entry of the listener and class in the XML file like the one given below:

Code:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<listeners>
<listener class-name="Demo.TestListener"></listener>
</listeners>
<test name="ListenerTest">
<classes>
<class name="Demo.Testing.class"></class>
</classes>
</test>
</suite> <!-- Suite -->

Output:
output2 listeners in testng

Conclusion

Above, the description of Listeners clearly gives the basic understanding of Listeners and how they are implemented in the Java program in order to customize the logs and reports. Before using any Listener, a clear understanding is required of all the Listeners and the specific scenarios in which they need to be used along with the methods they override.

Recommended Articles

This is a guide to Listeners in TestNG. Here we discuss methods of  Listeners in TestNG and two ways to create Listeners in TestNG. You can also go through our other related articles to learn more-

  1. Install TestNG
  2. Testing Frameworks for Java
  3. Java Annotations
  4. Overriding in Java
PROGRAMMING LANGUAGES Course
502+ Hours of HD Videos
54 Courses
4 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
SELENIUM Certification Course
57+ Hours of HD Videos
15 Courses
9 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
IOT System - Design & Develop an IOT System
65+ Hours of HD Videos
7 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
JENKINS Certification Course
19+ Hours of HD Videos
6 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
Primary Sidebar
Popular Course in this category
TESTNG Certification Course
 26+ Hours of HD Videos
6 Courses
Verifiable Certificate of Completion
  Lifetime Access
4.5
Price

View Course
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more