• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
EDUCBA

EDUCBA

MENUMENU
  • Resources
        • Java Tutorials

          • Cheat Sheet Java
          • Cheat Sheet Python
          • C# vs Js
        • Java Tutorials
        • Python Tutorials

          • Angular 5 vs Angular 4
          • Careers in Python
          • Kali Linux vs Ubuntu
        • Python Tutorials
        • Top Differences

          • Cheat Sheet JavaScript
          • Python Interview Questions
          • Cloud Computing or Virtualization
        • Top Differences
        • Others

          • Resources (A-Z)
          • Top Interview Question
          • Programming Languages
          • Web Development Tools
          • HTML CSS Tutorial
          • Technology Basics
          • Technology Careers
          • View All
  • Free Courses
  • All Courses
        • Certification Courses

          Software Development Course 2
        • All in One Bundle

          All-in-One-Software-Development-Bundle
        • Become a Python Developer

          Python-Certification-Training
        • Others

          • Java Course
          • Become a Selenium Automation Tester
          • Become an IoT Developer
          • Ruby on Rails Course
          • Angular JS Certification Training
          • View All
  • 600+ Courses All in One Bundle
  • Login

Listeners in TestNG

Home » Software Development » Blog » Software Development Basics » Listeners in TestNG

listeners in testng

Introduction to Listeners in TestNG

Before understanding Listeners in TestNG first, we will study Listeners and TestNG separately. There are times when we wish to modify the behavior of TestNG in our application and this can be done by Interfaces. 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 Listeners are used by the programmers is to create logs and create the custom reports according to the specific scenario defined.

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 are overridden by them:

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 methods of this interface in order 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 is failed as it indicates the failures of the test. 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 which are overridden:

  • onStart: This method is implemented before the invocation of the test suite which means all the code written inside it is run before the start of any suite.
  • onFinish: This method is implemented after the invocation of the test suite 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:

Popular Course in this category
Software Testing Training (11 Courses) 11 Online Courses | 60+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (1,230 ratings)
Course Price

View Course

Related Courses
Selenium Training Certification (9 Courses, 4+ Projects)Appium Training (2 Courses)JMeter Certification Training (3 Courses)

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 of adding the @listeners in specific classwork in a suite having 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 the methods of it 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 testngConclusion

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. AngularJS Events
  3. What is XPath?
  4. Testing Frameworks for Java
  5. Java Annotations
  6. Overriding in Java

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Reader Interactions
Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar
Technology Blog Tutorials
  • Software Development Basics
    • Interoperability Testing
    • Code Coverage
    • Test Plan Template
    • Domain Testing
    • Sanity Testing
    • React Tools
    • What is Switch?
    • Adhoc Testing
    • Equivalence Partitioning
    • Recovery Testing
    • Software Development
    • Black Box Testing Techniques
    • What is XPath?
    • Listeners in TestNG
    • Array vs ArrayList
    • Git Checkout
    • Haskell Alternatives
    • What is Polymorphism?
    • TestNG Annotations
    • Unix File System
    • Shell Script Parameters
    • Software Quality Assurance
    • What is SDET?
    • UML Deployment Diagram
    • Fuzz Testing
    • What is Defect?
    • Automation Testing
    • Static Testing Techniques
    • Install GRUB
    • Spike Testing
    • Exception Handling in VB.NET
    • Unix File Permissions
    • Mutation Testing
    • What is a Bug in Software Testing?
    • Mantis Bug Tracker
    • Compatibility Testing
    • Components of Selenium
    • Overriding in OOPs
    • Iterator in C++
    • Free Web Hosting Sites
    • Interface Testing
    • Dynamic Testing
    • Non Functional Testing
    • Regression Testing Tools
    • Scalability Testing
    • Volume Testing
    • Negative Testing
    • Performance Testing Life Cycle
    • What is XPath in Selenium?
    • What is Test Automation Frameworks?
    • Bootstrap Typography
    • What is Laravel?
    • Hive Built-in Functions
    • Stability Testing
    • Levels of Software Testing
    • Software Testing Life Cycle
    • Types of Domain
    • VB.NET Controls
    • Types of Websites
    • What is Cucumber?
    • Best C Compilers
    • Manual Testing
    • UML Component Diagram
    • What is Stress Testing?
    • What is Debugging?
    • Test Harness
    • Diffie Hellman Key Exchange Algorithm
    • What is Functional Testing?
    • Constructor in C++
    • TFTP
    • What is Web Hosting?
    • Types of Software Testing
    • Benchmark Testing
    • UML Diagram Softwares
    • UML Object Diagram
    • Test Coverage
    • Gantt Chart Software
    • What is FTP?
    • Static Testing
    • Python Frameworks
    • What is Usability Testing?
    • HTTP Cookies
    • RMI Architecture
    • Selenium Architecture
    • Defect Tracking Tools
    • Performance Testing Tools
    • Monolithic Kernel vs MicroKernel
    • Cryptosystems
    • IPv6 Header Format
    • What is Cross Site Scripting?
    • User Datagram Protocol
    • SOA Testing
    • Test Case Design Techniques
    • What is SVN?
    • What is Debian?
    • Bootstrap Components
    • Bootstrap Layout
    • Windows Commands
    • Kotlin Functions
    • DBMS Keys
    • Selenium Grid
    • Selenium Tools
    • List of few Errors In Website
    • Introduction To GIT
    • Internet of Things (IoT) Applications
    • Is Cassandra NoSQL
    • What is OLTP?
    • Introduction To Algorithm
    • What is Juypter Notebook
    • Git Alternatives
    • Introduction To Android
    • GitHub Alternatives
    • Introduction to Windows
    • What is an Algorithm
    • What is Maven
    • What Is Apache
    • What Is SDLC
    • Sharepoint Alternatives
    • Selenium Alternatives
    • What is Selenium
    • What is Shell Scripting
    • What is Mainframe
    • What is Software Development
    • What is Git
    • What is Computer Science
    • Uses Of Powershell
    • What is SSRS
    • What is Application Server
    • What is RMAN Oracle
    • What is Virtual Host
    • What is Desktop Software
    • System Design Interview Questions
    • What Is System Design
    • What Is Design Pattern
    • What is MVC Design Pattern
    • System Analysis And Design
    • Application Software & Types
    • Learn the Art of Mechatronics
    • Myths & Misconceptions Software
    • Solve Problems With Technology
    • Avoid Pitfalls of Shadow
    • Learn to Code For Beginners
    • Software as a Service (Saas)
    • Freelance Web Designer
    • CISA Certification Exam
    • Programming Concepts
    • Defect Life Cycle in Software Testing
    • What is Visual Studio Code
    • Gray Box Testing
    • What is GPS
    • What is WIX
    • Bootstrap 4 Cheat sheet
    • Increase Productivity With New Technology
    • Uses of Salesforce
    • Uses of Selenium
    • Uses Of C#
    • IntelliJ Cheat Sheet
    • What is Spiral Model
    • Monolithic Kernel
    • Uses Of WordPress
    • What is a Greedy Algorithm
    • What is OSPF
    • Is MySQL Programming Language
    • Is Blockchain the Future
    • What is JMS
    • WordPress Work
    • What is Web Application
    • HTML Image Tags
    • Boolean operators in Java
    • What is WebSocket
    • Introduction To PHP
    • Advantages Of Array
    • Python 3 cheat sheet
    • How JavaScript Works
    • Is Blockchain Safe
    • What is PLC
    • What is Threading
    • How Blockchain Works
    • SoapUI Alternatives
    • What is Microcontroller
    • Advantages of PHP
    • PHP Alternatives
    • Ubuntu Alternatives
    • WordPress Alternatives
    • Linux Alternatives
    • What is SOAP
    • Introduction To Computer Network
    • Windows Operators
    • Android Alternatives
    • What is PowerShell
    • What is Elasticsearch
    • Algorithm in Programming
    • JIRA Alternatives
    • Wix Alternatives
    • PowerShell Operators
    • What is Laravel Framework
    • SOA Alternatives
    • Is Ansible free
    • Laravel Commands
    • What is Blockchain Technology
    • What is Bootstrap
    • What is Unix
    • What is Ansible
    • What is Software Testing
    • Windows Alternatives
    • What is Jira Software
    • What is UI Designer
    • What is VBScript
    • What is SoapUI
    • Uses of Ubuntu
    • What is MVC
    • What is ASP.NET
    • What is Multithreading
    • What is ASP.Net Web Services
    • What is TFS
    • What is DBMS
    • What is Embedded Systems
    • Inheritance in VB.Net
    • What is VMware?
    • What is Open-Source License
    • What is Bot
    • What is Open Source
    • What is ETL Testing
    • What is GraphQL
    • cPanel vs Plesk
    • System Software Tools
    • Information Technology Benefits
    • Black Box Testing
    • What is ETL
    • What is IDE
    • Uses of Coding
    • Uses Of Raspberry Pi
    • What is Hypervisor
    • Website Services
    • What is Common Gateway Interface
    • White Box Testing
    • Web Testing Application
    • OS Alternatives
    • Iterative Model
    • What is Unix Shell
    • Automation Testing Tools
    • Integration Testing
    • System Testing
    • Unit Testing
    • Test Automation Framework
    • Alpha and Beta Testing
    • Decision Table Testing
    • Regression Testing
    • Types of Algorithms
    • What is Appium
    • Prototype Model
    • What is CLI
    • Waterfall Model
    • RAD Model
    • Ray Tracing Algorithm
    • OpenGL in Android
    • Types of UML Diagrams
    • Class Diagram
    • What is Assembly Language
    • ASP.NET Page Life Cycle
    • HTTP Caching
    • What is Selenium Web Driver
    • Selenium Framework
    • Selenium Testing
    • Selenium Automation Testing
    • What is Buffer Overflow
    • What is Joomla
    • What is Virtualization
    • What is WCF
    • What is OOP
    • What is SOA
    • What is JDBC
    • What is Clickbait
    • What is GUI
    • What is FreeBSD
    • Software Testing Principles
    • System Integration Testing
    • What is CMD
    • What is VB.Net
    • What is CodeIgniter
    • UML Use Case Diagram
    • What is WordPress
    • UML Activity Diagram
    • What is Coding
    • UNIX ARCHITECTURE
    • Random Forest Algorithm
    • UML Sequence Diagram
    • DOS vs Windows
    • What is SVG
    • What is QTP
    • VB.NET Operators
    • What is MuleSoft
    • What is Exploratory Testing
    • What is Ransomware
    • Sublime Text Alternatives
    • What is Static Routing
    • Kotlin vs Swift
    • GUI vs CLI
    • What is CentOS
    • What is Template Class in C++
    • What is Apex
    • StringBuffer vs StringBuilder
    • DES vs AES
    • Encryption vs Decryption
    • Dynamic Routing
    • Cyclomatic Complexity
    • Encryption Algorithm
    • Install Kali Linux
    • Alpha Testing vs Beta Testing
    • What is DHCP
    • Basic HTML Tags
    • Advantages of C
    • ASP.Net Validation Controls
    • What is CSRF
    • Network Mapper
    • Loops in C++
    • Loops in C
    • EJB vs Spring
    • Switch Statement in C
    • CentOS Commands
    • Digital Signature Softwares
  • Database Management (71+)
  • Ethical Hacking Tutorial (33+)
  • HTML CSS Tutorial (47+)
  • Installation of Software (54+)
  • Top Interview question (188+)
  • Java Tutorials (196+)
  • JavaScript (71+)
  • Linux tutorial (32+)
  • Network Security (85+)
  • Programming Languages (232+)
  • Python Tutorials (89+)
  • Software Development Careers (38+)
  • SQL Tutorial (33+)
  • String Functions (12+)
  • Technology Commands (38+)
  • Top Differences (368+)
  • Web Development Tools (33+)
  • Mobile App (60+)
Technology Blog Courses
  • Software Testing Training
  • Selenium Training Certification
  • Appium Training
  • JMeter Certification Training
Footer
About Us
  • Who is EDUCBA?
  • Sign Up
  •  
Free Courses
  • Free Course Programming
  • Free course Python
  • Free Course Java
  • Free Course Javascript
  • Free Course on SQL
  • Free Course on Web Design
  • Free HTML Course
  • Free Android App Development Course
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
  • Ruby on Rails Course
  • ASP.NET Course
  • VB.NET Course
  • Bootstrap Training Course
  • Become a Linux System Administrator
  • PHP Course
  • Joomla Training
  • HTML Course
Resources
  • Resources (A To Z)
  • Java Tutorials
  • Python Tutorials
  • Top Differences
  • Top Interview Question
  • Programming Languages
  • Web Development Tools
  • HTML CSS Tutorial
  • Technology Basics
  • Technology Careers
  • Ethical Hacking Tutorial
  • SQL Tutorials
  • Digital Marketing
Apps
  • iPhone & iPad
  • Android
Support
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions

© 2019 - 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
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
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
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

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 Login

Forgot Password?

Let’s Get Started
Please provide your Email ID
Email ID is incorrect

Limited Period Offer - All in One Software Development Bundle (600+ Courses, 50+ projects) View More

Limited Period Offer - Limited Period Offer - All in One Software Development Bundle (600+ Courses, 50+ projects) View More