EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Software Testing Tutorial Listeners in TestNG
Secondary Sidebar
Software Testing Tutorial
  • Advance
    • Cyclomatic Complexity
    • Decision Table Testing
    • Decision Tree Algorithm
    • What is Continuous Integration
    • Mantis Bug Tracker
    • Equivalence Partitioning
    • Gantt Chart Software
    • Acceptance Testing Types
    • Load testing tools
    • Install TestNG
    • Install Unity
    • Defect Management Process
    • Test Plan Template
    • Testing Interview Questions
    • Testing of Mobile application
    • What is Test Automation Frameworks
    • Test Automation Framework
    • Application of Automation
    • Test Automation Process
    • Automation Testing Roles and Responsibilities
    • What is Instruction Cycle?
    • What is Cucumber?
    • 15 Best Popular Bug Reporting Tools
    • What is Automated Testing?
    • Software Maintenance Types
    • Types of Penetration Testing
    • Software Reliability
    • Best Gantt Chart Software
    • Code Coverage
    • Branch Coverage
    • Decision Coverage
    • Statement Coverage
    • What is Test Case
    • Types of Test Case
    • What is Test Scenario
    • Formal Review
    • Alpha Beta Pruning
    • What is Cyclomatic Complexity?
    • Test Coverage
    • How to Write Test Case
    • Testing Documentation
    • Performance Testing Life Cycle
    • Test Harness
    • Test Strategy
    • Software Incident Management
    • What is Debugging
    • What is Defect?
    • Listeners in TestNG
  • Basics
    • What is Software Testing
    • Careers in Software Testing
    • Defect Life Cycle in Software Testing
    • Bug Life Cycle
    • Levels of Software Testing
    • Software Testing Life Cycle
    • Software Tester Work
    • Software Testing Principles
    • Software Testing Services
    • Testing Methodologies
    • Test Approaches
    • Grey Box Testing
    • Types of Software Testing
    • What is a Bug in Software Testing
    • Benefits of Automation Testing
    • What is Automation Testing?
    • Types of Automation
    • Typical Journey of a Software Tester
    • Automation Testing Process
    • Mobile Automation Testing
    • Automation Testing Life Cycle
    • Software Quality Assurance
    • Software Quality Assurance
    • What is Test Environment?
    • Verification and Validation Testing
  • Types of Testing
    • Adhoc Testing
    • Types of System Testing
    • Manual Testing Types
    • Unit Testing Types
    • Unit Testing Benefits
    • Agile Testing
    • What is Agile Testing
    • Acceptance Testing
    • Stress Testing Types
    • Alpha and Beta Testing
    • Application Testing
    • Automation Testing
    • Automation Testing Advantages
    • Benchmark Testing
    • Black Box Testing
    • Domain Testing
    • Dynamic Testing
    • Ecommerce Testing
    • Fuzz Testing
    • Gray Box Testing
    • GUI Testing
    • Installation Testing
    • Interface Testing
    • Interoperability Testing
    • Mainframe Testing
    • Manual Testing
    • Mutation Testing
    • Monkey Testing
    • Negative Testing
    • Penetration Testing
    • Penetration testing phases
    • Penetration testing framework
    • Protocol Testing
    • Recovery Testing
    • Regression Testing
    • Mobile Penetration Testing
    • Accessibility Testing
    • Sanity Testing
    • Scalability Testing
    • Security Testing
    • Spike Testing
    • Stability Testing
    • State Transition Testing
    • Static Testing
    • Gatling Load Testing
    • System Integration Testing
    • Structural Testing
    • Locust Load Testing
    • System Testing
    • Control Flow Testing
    • Unit Testing
    • Cypress testing
    • Volume Testing
    • Web Testing Application
    • What is Exploratory Testing
    • What is Stress Testing
    • What is Usability Testing
    • White Box Testing
    • Types of White Box Testing
    • Compatibility Testing?
    • Use Case Testing
    • Beta Testing
    • Integration Testing
    • Non Functional Testing
    • Non Functional Testing Types
    • What is Functional Testing
    • Functional testing types
    • Cookie Testing
    • Alpha Testing
    • Boundary Value Testing
    • Equivalence Class Testing
    • Glass Box Testing
    • SOA Testing
    • Smoke Testing
    • Visual Testing
    • Visual Paradigm
    • Model-Based Testing
  • Testing techniques
    • Software Testing Methodologies
    • Black Box Testing Techniques
    • Static Testing Techniques
    • Test Case Design Techniques
    • What is Static Analysis
  • Testing tools
    • Manual Testing Tools
    • Visual Testing Tools
    • Automation Testing Tools
    • Functional Testing Tools
    • GUI Testing Tools
    • Penetration Testing Tools
    • Performance Testing Tools
    • SOA Testing Tools
    • Accessibility Testing Tools
    • What is QTP
    • Regression Testing Tools
    • Security Testing Tools
    • Test Management Tools
    • Defect Management Tools
    • Code Coverage Tools
    • Test Coverage Tools
    • Defect Tracking Tools
    • Continuous Integration Tools
    • Install Bugzilla
    • Test data generation tool
    • Unit Testing Tools
    • Web Testing Tools
    • Stress Testing Tools
    • Performance Monitoring Tools
    • Mobile Testing Tools
    • Responsive Testing Tool
    • Cross Browser Testing Tools
    • Risk Based Testing
    • Database Testing Tools
    • WinRunner
    • What is Squish?
    • CubicTest
    • What is WinRM?
    • Bugzilla Tool
    • Code review tools
    • Penetration Testing Open Source Tools
  • Inteview Questions
    • Automation Testing Interview Questions
    • Manual Testing Interview Questions
    • ISTQB Interview Questions
    • Cucumber Interview Questions
    • Software Testing Interview Questions
    • Penetration Testing Interview Questions

Related Courses

Software Testing Course

Penetration Training Course

TestNG Training Course

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:

  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:

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,328 ratings)

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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • 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
Popular Course in this category
Selenium Automation Testing Training (11 Courses, 4+ Projects, 4 Quizzes)
  11 Online Courses |  4 Hands-on Projects |  45+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Software Testing Training (11 Courses, 2 Projects)4.9
Penetration Testing Training Program (2 Courses)4.8
TestNG Training (4 Courses, 2 Project)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
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

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

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

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

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

EDUCBA Login

Forgot Password?

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

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

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

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

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

Let’s Get Started

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