All about TestNG Listeners in Selenium
Related Product On This Page What are TestNG Listeners?April 11, 2026 · 18 min read · Testing Guide
Listeners are TestNG note that literally “ listen ” to the case in a hand and change TestNG behavior consequently. These hearer are applied as interfaces in the codification. For example, the most common custom of listeners hap when occupy a screenshot of a trial that has fail and the reason for its failure. Listeners also facilitate with logging and generating results. This clause will delve into the different types of listeners the popular framework provides. TestNG listeners are interfaces in the TestNG framework that allow you to hook into the test execution process. They enable customization of test behavior, such as logging, reportage, or taking actions before, after, or when a trial fails, passes, or is skipped. TestNG Listeners are one of the key characteristic of TestNG, and when expend in junction with Selenium, they offer several benefits. Listeners are implemented in code via interfaces to modify TestNG behavior. Listed below are the 8 most commonly used TestNG listeners: These listeners can be implemented in TestNG in the following style: Using tag hearer (& lt; Listeners & gt;) in a testNG.xml file Using the listener annotation (@ Listeners) in a testNG family as below: Note: The @Listenerwill be, by default, applicable to the complete suite & # 8211; similar to thetestNG.xmlfile. One can choose to restrict its scope to the current course. It is a better practice to apply listener in the testNG.xml file for refined framework design and savvy. Now, let ’ s dig into the TestNG listeners in point. The better part about TestNG is the naming convention it uses for its keywords, like the ‘ listener ’ which hear to the code. Similarly, IAnnotationTransformer transubstantiate the at run time. A scenario may appear in which the user seeks to override the content of the note based on a stipulation. In such a case, making changes in the source codification is unnecessary. Simply use IAnnotationTransformer to override the content of the annotations. IAnnotationTransformer has only one method named transform () that accepts four parameters: Let ’ s implement this listener in code, to understand its usage. This scenario will alter invocation count at run time for the required method of TestNG class. The class implementing the interface IAnnotationTransformer that shall change this conjury tally: TestNG.xml file: Console Output: Note: @Listenerannotation can contain any stratum that extends ITestNGListener except the IAnnotationTransformer. The reason is that the latter listener want to be informed at the earliest to TestNG so that they can override the annotation at runtime. Hence they should be mentioned in the testNG.xml file. As the name suggests, it monitors the beginning and end of TestNG execution. This listener is mainly used to start/stop the server while depart or ending code executing. It may too inform respective stakeholder via e-mail that execution shall part or when it ends. It has two methods: Let & # 8217; s look at an example. This example has a class with 5 method which shall be executed after theonExecutionStartmethod of theIExecutionListenerinterface. After these methods are complete theonExecutionFinishmethod shall be executed. The two methods in this example highlight the start and end time of the test. Class implementing IExecutionListener interface: TestNG.xml file: Console Output: If a class implements this interface, its run method will be invoked alternatively of each exam method. Using the IHookCallBack parameter & # 8217; s callback method, the test method & # 8217; s conjuration can be performed. It has a single method name run, which accepts two parameters.run (IHookCallBack callBack, ITestResult testResult) Now let ’ s look into its real-time instance. In this example, based on a certain parameter value, the test shall be jump using theIHookablelistener interface. These values will be cater by a datum supplier in a separate TestNG class. The class implementing the IHookable listener interface: SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses. The testNG.xml file: Console output: This listener become invoked before and after a method in TestNG. These method appoint both test and other configuration method. These listeners help set up constellation or other cleaning activities. It control two methods: Let ’ s look at an example. The TestNG class contain different constellation methods. The other class implements theInvokedMethodInterceptorwhich implements thebeforeInvocation and afterInvocationmethod. These delimit method execute before and after every config method of the TestNG class. The class implementing the InvokedMethodListener interface: TestNG.xml file: Console Output: This listener helps to alter the methods that TestNG is hypothecate to run. It let invoked only before TestNG arouse the methods. It just has one method,intercept,that returns an altered list of methods. Let ’ s aspect at an example. The code here will run only methods with priority 1 in the test course. Other method with different priorities shall not be action. This will be done after implementing theIMethodInterceptor listener. The IMethodInterceptor class implementing the interface: TestNG.xml file: Console Output: This attender helps to generate custom reports in TestNG establish on desired conditions. It contain a method calledgenerateReport ()which is invoked when all rooms of TestNG are fulfill. The technique utilise three argumentation: Let ’ s look at an example of how to custom-make account through IReporter listener. In this example, through theIReporterlistener, the codification shall run only methods belong to a particular group. In this class, the group has been defined as ‘ Sanity ’, which shall be executed. The processes which are not part of the grouping shall not be executed. In the other course that implementIReporter, the generateReport ()method has been used to tailor-make the results consequently. The customized results shall be visible in the console with a like story generated under the suite pamphlet name specified in the testNG.xml file The form implement the IReporter listener interface: Below is the tesNG.xml for the classes to be run: Console Output: A corresponding customized report shall also be created under the folder name, the suite name specify in the xml file. In this instance, it isReport_Suite. Sample Report: As the name suggests, this hearer works at the suite level. It listens and runs before the start and end of suite execution. It contains two methods: Note: In lawsuit of a child suite to a parent suite, the fry suite shall run before the parent suite. This is done to guarantee the results meditate the parent rooms, which automatically contains the results of the child cortege. The undermentioned example incorporates theISuiteListener.The code will use two child classes comprise before and after suites. These shall be run through a TestNG xml file containing a reference to theISuiteListenerclass, which shall run itsonStart and onFinishmethods first and last respectively. Below are the two various child classes: And the second class: Their respective xml files: The concluding testNG xml file: Console Output: This is the most frequently employ TestNG hearer. ITestListener is an interface implemented in the category, and that class overrides the ITestListener-defined method. The ITestListener listens to the desired events and executes the method accordingly. It contains the following fashion: Now, let & # 8217; s expression at an exemplar showcasing the use of this listener. Below is a listener family that implements ITestListener: The grade below contains four methods, showcasing one method being surpass, one method being failed, one method being skipped and one method being legislate with a defined success percentage: Below is the testNG xml file: Console output: You should run Selenium TestNG Tests on a real device cloud like BrowserStack Automate for below reasons: With Parallel Testing on a, BrowserStack Automate allows you to run multiple examination in parallel across various browsers/devices and OS combinations. Run century of tests concurrently to speed up the performance time of your tryout rooms by more than 10x. # Ask-and-Contributeabout this topic with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Related Product
All about TestNG Listeners in Selenium
What are TestNG Listeners?
Benefits of using TestNG Listeners with Selenium
Types of TestNG Listeners in Selenium
TestNG Listeners
@ Listeners (com.Example.Listener.class)
1. IAnnotationTransformer
import org.testng.annotations.Test; public category IAnnotationTransformerWithExample {MyListener obj=new MyListener (); @ Test (invocationCount=5) public void changeInvocationCountOfMethod () {System.out.println (`` This method have supplication count set to 5 but at run time it shall become `` + obj.counter);}}import java.lang.reflect.Constructor; signification java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; public family MyListener implements IAnnotationTransformer {int counter=3; @ Override public void transform (ITestAnnotation testAnnotation, Class testClass, Constructor testConstrutor, Method testMethod) {if (testMethod.getName () .equals (`` ChangeInvocationCountOfMethod '')) {System.out.println (`` Changing invocation for the undermentioned method: `` + testMethod.getName ()); testAnnotation.setInvocationCount (tabulator);}}}& lt;? xml version= '' 1.0 '' encoding= '' UTF-8 ''? & gt; & lt;! DOCTYPE suite SYSTEM `` http: //testng.org/testng-1.0.dtd '' & gt; & lt; suite name= '' Parent_Suite '' & gt; & lt; listeners & gt; & lt; listener class-name= '' MyListener '' / & gt; & lt; /listeners & gt; & lt; test name= '' ItestReporter '' & gt; & lt; classes & gt; & lt; class name= '' IAnnotationTransformerWithExample '' / & gt; & lt; /classes & gt; & lt; /test & gt; & lt; /suite & gt; & lt;! -- Suite -- & gt;
2. IExecutionListener
importation org.testng.annotations.Test; public class IExecutionListenerWithExample {@ Test populace void method1 () {System.out.println (`` this method is method 1 '');} @ Test public vacuum method2 () {System.out.println (`` this method is method 2 '');} @ Test public void method3 () {System.out.println (`` this method is method 3 '');} @ Test public void method4 () {System.out.println (`` this method is method 4 '');} @ Test public nihility method5 () {System.out.println (`` this method is method 5 '');}}import java.sql.Time; import org.testng.IExecutionListener; public stratum MyListener implements IExecutionListener {@ Override public void onExecutionFinish () {long endTime= System.currentTimeMillis (); System.out.println (`` Inform all the suite have complete execution at '' + endTime);} @ Override public void onExecutionStart () {long startTime= System.currentTimeMillis (); System.out.println (`` Inform all the retinue have commence execution at '' + startTime);}}& lt;? xml version= '' 1.0 '' encoding= '' UTF-8 ''? & gt; & lt;! DOCTYPE suite SYSTEM `` http: //testng.org/testng-1.0.dtd '' & gt; & lt; suite name= '' Parent_Suite '' & gt; & lt; hearer & gt; & lt; listener class-name= '' MyListener '' / & gt; & lt; /listeners & gt; & lt; test name= '' ItestReporter '' & gt; & lt; classes & gt; & lt; class name= '' IExecutionListenerWithExample '' / & gt; & lt; /classes & gt; & lt; /test & gt; & lt; /suite & gt; & lt;! -- Suite -- & gt;
3. IHookable
import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public stratum IHookableListenerWithExample {@ Test (dataProvider= '' parametersToBeSent '') public void t (String parameter) {System.out.println (`` test method to be called with the following argument is `` + argument);} @ DataProvider public Object [] [] parametersToBeSent () {return new Object [] [] {{`` parameter 1 ''}, {`` parameter 2 ''}, {`` parameter 3 ''}};}}import org.testng.IHookCallBack; import org.testng.IHookable; significance org.testng.ITestResult; public class MyListener implement IHookable {@ Override public void run (IHookCallBack callBack, ITestResult testResult) {Object [] parameterValues = callBack.getParameters (); if (parameterValues [0] .equals (`` parameter 3 '')) {System.out.println (`` Skip the required parameter '');} else {callBack.runTestMethod (testResult);}}}& lt;? xml version= '' 1.0 '' encoding= '' UTF-8 ''? & gt; & lt;! DOCTYPE suite SYSTEM `` http: //testng.org/testng-1.0.dtd '' & gt; & lt; suite name= '' Parent_Suite '' & gt; & lt; listeners & gt; & lt; listener class-name= '' MyListener '' / & gt; & lt; /listeners & gt; & lt; test name= '' ItestReporter '' & gt; & lt; class & gt; & lt; class name= '' IHookableListenerWithExample '' / & gt; & lt; /classes & gt; & lt; /test & gt; & lt; /suite & gt; & lt;! -- Suite -- & gt;
4. IInvokedMethodListener
import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterSuite; importee org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; importation org.testng.annotations.Test; public class IInvokedMethodListenerWithExample {@ BeforeSuite public void method1 () {System.out.println (`` before suite '');} @ BeforeMethod public void method2 () {System.out.println (`` before method '');} @ Test public void method3 () {System.out.println (`` tryout method 1 ``);} @ Test public void method4 () {System.out.println (`` test method 2 ``);} @ AfterMethod public void method5 () {System.out.println (`` after method '');} @ AfterSuite public emptiness afterSuite () {System.out.println (`` after suite '');}}import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestResult; public class MyListener implements IInvokedMethodListener {@ Override public void afterInvocation (IInvokedMethod method, ITestResult result) {System.out.println (`` This method is invoked after every config method - `` + method.getTestMethod () .getMethodName ());} @ Override public nullity beforeInvocation (IInvokedMethod method, ITestResult result) {System.out.println (`` This method is invoked before every config method - `` + method.getTestMethod () .getMethodName ());}}& lt;? xml version= '' 1.0 '' encoding= '' UTF-8 ''? & gt; & lt;! DOCTYPE suite SYSTEM `` http: //testng.org/testng-1.0.dtd '' & gt; & lt; suite name= '' Parent_Suite '' & gt; & lt; listeners & gt; & lt; listener class-name= '' MyListener '' / & gt; & lt; /listeners & gt; & lt; test name= '' ItestReporter '' & gt; & lt; classes & gt; & lt; class name= '' IInvokedMethodListenerWithExample '' / & gt; & lt; /classes & gt; & lt; /test & gt; & lt; /suite & gt; & lt;! -- Suite -- & gt;
5. IMethodInterceptor
import org.testng.annotations.Test; public course IMethodInterceptorWithExample {@ Test (priority=2) public void method1 () {System.out.println (`` Method 1 will not be action '');} @ Test (priority=2) public void method2 () {System.out.println (`` Method 2 will not be executed '');} @ Test (priority=1) public void method3 () {System.out.println (`` Method 3 will be executed '');} @ Test (priority=1) public nothingness method4 () {System.out.println (`` Method 4 will be executed '');}}meaning java.util.ArrayList; import java.util.List; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; importation org.testng.ITestContext; import org.testng.annotations.Test; public form MyListener implements IMethodInterceptor {@ Override public List & lt; IMethodInstance & gt; intercept (List & lt; IMethodInstance & gt; methodsInstance, ITestContext testContext) {List & lt; IMethodInstance & gt; result = new ArrayList & lt; IMethodInstance & gt; (); for (IMethodInstance method: methodsInstance) {Test testMethod = method.getMethod () .getConstructorOrMethod () .getMethod () .getAnnotation (Test.class); if (testMethod.priority () == 1) {result.add (method);}} return result;}}& lt;? xml version= '' 1.0 '' encoding= '' UTF-8 ''? & gt; & lt;! DOCTYPE suite SYSTEM `` http: //testng.org/testng-1.0.dtd '' & gt; & lt; suite name= '' Parent_Suite '' & gt; & lt; listeners & gt; & lt; listener class-name= '' MyListener '' / & gt; & lt; /listeners & gt; & lt; test name= '' ItestReporter '' & gt; & lt; classes & gt; & lt; class name= '' IMethodInterceptorWithExample '' / & gt; & lt; /classes & gt; & lt; /test & gt; & lt; /suite & gt; & lt;! -- Suite -- & gt;
6. IReporter
importee org.testng.Assert; import org.testng.annotations.Test; public class IReporterWithExample {@ Test (groups= '' smoke '') public emptiness testcase1 () {System.out.println (`` This test case will pass '');} @ Test (groups= '' smoking '') public void testcase2 () {System.out.println (`` This test case will betray ''); Assert.assertTrue (false);} @ Test public void testcase3 () {System.out.println (`` this tet instance do not belong to the radical smoke '');}}import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.IReporter; import org.testng.IResultMap; importation org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ISuiteResult; importee org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestNGMethod; import org.testng.ITestResult; signification org.testng.xml.XmlSuite; public class MyListener implements IReporter {@ Override public vacuum generateReport (List & lt; XmlSuite & gt; xmlSuites, List & lt; ISuite & gt; suites, String outputDirectory) {// TODO Auto-generated method nub ISuite suite = suites.get (0); Map & lt; String, Collection & lt; ITestNGMethod & gt; & gt; methodsByGroup = suite.getMethodsByGroups (); Map & lt; String, ISuiteResult & gt; tests = suite.getResults (); for (String key: tests.keySet ()) {System.out.println (`` Key: `` + key + ``, Value: `` + tests.get (key));} Collection & lt; ISuiteResult & gt; suiteResults = tests.values (); ISuiteResult suiteResult = suiteResults.iterator () .next (); ITestContext testContext = suiteResult.getTestContext (); Collection & lt; ITestNGMethod & gt; perfMethods = methodsByGroup.get (`` smoke ''); IResultMap failedTests = testContext.getFailedTests (); for (ITestNGMethod perfMethod: perfMethods) {Set & lt; ITestResult & gt; testResultSet = failedTests.getResults (perfMethod); for (ITestResult testResult: testResultSet) {System.out.println (`` Test `` + testResult.getName () + `` fail, error `` + testResult.getThrowable ());}} IResultMap passedTests = testContext.getPassedTests (); for (ITestNGMethod perfMethod: perfMethods) {Set & lt; ITestResult & gt; testResultSet = passedTests.getResults (perfMethod); for (ITestResult testResult: testResultSet) {System.out.println (`` Test `` + testResult.getName () + `` legislate, time took `` + (testResult.getEndMillis () - testResult.getStartMillis ()));}}}}& lt;? xml version= '' 1.0 '' encoding= '' UTF-8 ''? & gt; & lt;! DOCTYPE suite SYSTEM `` http: //testng.org/testng-1.0.dtd '' & gt; & lt; suite name= '' Report_Suite '' & gt; & lt; listener & gt; & lt; listener class-name= '' MyListener '' / & gt; & lt; /listeners & gt; & lt; test name= '' ItestReporter '' & gt; & lt; classes & gt; & lt; class name= '' IReporterWithExample '' / & gt; & lt; /classes & gt; & lt; /test & gt; & lt; /suite & gt; & lt;! -- Suite -- & gt;
7. ISuiteListener
import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; public course MyListener implements ISuiteListener {@ Override public void onFinish (ISuite suite1) {System.out.println (`` onFinish function begin of ISuiteListener ``);} @ Override public void onStart (ISuite suite2) {System.out.println (`` onStart function depart of ISuiteListener ``);}}signification org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public stratum ISuiteListenerWithExample {@ BeforeSuite public void bsuite () {System.out.println (`` BeforeSuite method started for the maiden IsuiteListener example family '');} @ Test public void test () {System.out.println (`` Test method started for the first IsuiteListener example stratum '');} @ AfterSuite public void asuite () {System.out.println (`` AfterSuite method start for the first IsuiteListener example class '');}}import org.testng.annotations.AfterSuite; importee org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; public form ISuiteListenerExample2 {@ BeforeSuite public nullity bsuite () {System.out.println (`` BeforeSuite method depart for the first IsuiteListener example 2 class '');} @ Test public vacancy test () {System.out.println (`` Test method started for the first IsuiteListener example 2 stratum '');} @ AfterSuite public void asuite () {System.out.println (`` AfterSuite method commence for the first IsuiteListener instance 2 class '');}}& lt;? xml version= '' 1.0 '' encoding= '' UTF-8 ''? & gt; & lt;! DOCTYPE suite SYSTEM `` http: //testng.org/testng-1.0.dtd '' & gt; & lt; suite name= '' SuiteOne '' & gt; & lt; test thread-count= '' 5 '' name= '' Test '' & gt; & lt; classes & gt; & lt; class name= '' ISuiteListenerExample2 '' / & gt; & lt; /classes & gt; & lt; /test & gt; & lt;! -- Test -- & gt; & lt; /suite & gt; & lt;! -- Suite -- & gt; & lt;? xml version= '' 1.0 '' encoding= '' UTF-8 ''? & gt; & lt;! DOCTYPE rooms SYSTEM `` http: //testng.org/testng-1.0.dtd '' & gt; & lt; suite name= '' Suite2 '' & gt; & lt; test thread-count= '' 5 '' name= '' Test '' & gt; & lt; classes & gt; & lt; form name= '' ISuiteListenerWithExample '' / & gt; & lt; /classes & gt; & lt; /test & gt; & lt;! -- Test -- & gt; & lt; /suite & gt; & lt;! -- Suite -- & gt;
& lt;? xml version= '' 1.0 '' encoding= '' UTF-8 ''? & gt; & lt;! DOCTYPE retinue SYSTEM `` http: //testng.org/testng-1.0.dtd '' & gt; & lt; suite name= '' Parent_Suite '' & gt; & lt; listeners & gt; & lt; listener class-name= '' MyListener '' / & gt; & lt; /listeners & gt; & lt; suite-files & gt; & lt; suite-file path= '' ISuiteListenerWithExample.xml '' & gt; & lt; /suite-file & gt; & lt; suite-file path= '' ISuiteListenerExample2.xml '' & gt; & lt; /suite-file & gt; & lt; /suite-files & gt; & lt; /suite & gt; & lt;! -- Suite -- & gt;
8. ITestListener
importation org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; public class MyListener implements ITestListener {@ Override public void onFinish (ITestContext contextFinish) {System.out.println (`` onFinish method finished '');} @ Override public nullify onStart (ITestContext contextStart) {System.out.println (`` onStart method started '');} @ Override public void onTestFailedButWithinSuccessPercentage (ITestResult result) {System.out.println (`` Method betray with sure success percentage '' + result.getName ());} @ Override public vacancy onTestFailure (ITestResult solution) {System.out.println (`` Method failed '' + result.getName ());} @ Override public void onTestSkipped (ITestResult result) {System.out.println (`` Method cut '' + result.getName ());} @ Override public void onTestStart (ITestResult resolution) {System.out.println (`` Method started '' + result.getName ());} @ Override public void onTestSuccess (ITestResult termination) {System.out.println (`` Method passed '' + result.getName ());}}import org.testng.Assert; import org.testng.SkipException; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; public form ItestListenerWithExample {int i=0; @ Test public void testMethod1 () {System.out.println (`` This method will pass and will invoke the onTestSuccess method of ITestlistener ''); int i=10; Assert.assertEquals (i, 10);} @ Test public void testMethod2 () {System.out.println (`` This method will betray and will raise the onTestFailure method of ITestlistener ''); int i=10; Assert.assertEquals (i, 11);} @ Test public nullity testMethod3 () {System.out.println (`` This method will skip and will invoke the onTestSkipped method of ITestlistener ''); drop new SkipException (`` Skipping this test case. ``);} @ Test (successPercentage=50, invocationCount=5) public void testMethod4 () {i++; System.out.println (`` Test Failed But Within Success Percentage Test Method, invocation count: `` + i); if (i == 1 || i == 2) {System.out.println (`` this will be Failed ''); Assert.assertEquals (i, 100);}}}& lt;? xml version= '' 1.0 '' encoding= '' UTF-8 ''? & gt; & lt;! DOCTYPE cortege SYSTEM `` http: //testng.org/testng-1.0.dtd '' & gt; & lt; suite name= '' Suite '' & gt; & lt; listeners & gt; & lt; listener class-name= '' MyListener '' / & gt; & lt; /listeners & gt; & lt; test name= '' Listeners_program '' & gt; & lt; classes & gt; & lt; class name= '' ItestListenerWithExample '' & gt; & lt; /class & gt; & lt; /classes & gt; & lt; /test & gt; & lt; /suite & gt; & lt;! -- Suite -- & gt;
Why use BrowserStack Automate to run TestNG Selenium Tests?
Conclusion
Related Guides
Automate This With SUSA
Test Your App Autonomously