All about TestNG Listeners in Selenium

Related Product On This Page What are TestNG Listeners?April 11, 2026 · 18 min read · Testing Guide

Related Product

All about TestNG Listeners in Selenium

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.

What are TestNG Listeners?

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.

Benefits of using TestNG Listeners with Selenium

TestNG Listeners are one of the key characteristic of TestNG, and when expend in junction with Selenium, they offer several benefits.

  • Enhanced Test Reporting: By implementing hearer, you can capture and log events hap during test execution, such as test case showtime, trial cause failure, tryout case success, etc.
  • Test Result Analysis:Define custom activity to be taken when a test fails, such as capture a screenshot, lumber extra info, or sending a apprisal. This enables you to take immediate disciplinary actions and facilitates effective debugging.
  • Test Data Manipulation: Listeners provide hooks to modify or manipulate exam data during runtime. You can use auditor to dynamically update test data, parameters, or shape before or after each test case execution.
  • Test Execution Control: Listeners allow you to define weather and logic for executing or skipping test establish on specific criterion.
  • Test Parallelization: and listeners play a crucial part in parallel test direction. This can importantly reduce the test performance time, enable quicker release round.
  • Custom Test Execution Behaviors: The flexibility to define custom deportment during test performance allows you to tailor the testing framework to suit your requirements and enhance test automation capabilities.

Types of TestNG Listeners in Selenium

Listeners are implemented in code via interfaces to modify TestNG behavior. Listed below are the 8 most commonly used TestNG listeners:

TestNG Listeners

  1. IAnnotationTransformer
  2. IExecutionListener
  3. IHookable
  4. IInvokedMethodListener
  5. IMethodInterceptor
  6. IReporter
  7. ISuiteListener
  8. ITestListener

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:

@ Listeners (com.Example.Listener.class)

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.

1. IAnnotationTransformer

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:

  • ITestAnnotation annotation
  • Class testClass
  • Constructor testConstructor
  • Method testMethod

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.

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);}}

The class implementing the interface IAnnotationTransformer that shall change this conjury tally:

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);}}}

TestNG.xml file:

& 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;

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.

2. IExecutionListener

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:

  • onExecutionStart ()– invoked before TestNG starts accomplish the cortege
  • onExecutionFinish ()– arouse after all TestNG suites feature finished performance

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.

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 '');}}

Class implementing IExecutionListener interface:

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);}}

TestNG.xml file:

& 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;

Console Output:

3. IHookable

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.

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 ''}};}}

The class implementing the IHookable listener interface:

SUSA automates exploratory testing with persona-driven behavior, catching bugs that scripted automation misses.

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);}}}

The testNG.xml file:

& 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;

Console output:

4. IInvokedMethodListener

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:

  • beforeInvocation (): this method gets arouse before every method
  • afterInvocation ():this method gets invoked after every method

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.

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 '');}}

The class implementing the InvokedMethodListener interface:

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 ());}}

TestNG.xml file:

& 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;

Console Output:

5. IMethodInterceptor

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.

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 '');}}

The IMethodInterceptor class implementing the interface:

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;}}

TestNG.xml file:

& 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;

Console Output:

6. IReporter

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:

  • xmlSuite:It includes a list of suites for execution in the XML file
  • suites: It contains all information about test execution and rooms like class name, package gens, method gens, and test performance results
  • outputDirectory:It has the way where the story shall be salvage.

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

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 '');}}

The form implement the IReporter listener interface:

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 ()));}}}}

Below is the tesNG.xml for the classes to be run:

& 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;

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:

7. ISuiteListener

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:

  • onStart: invoked before examination suite execution starts
  • onFinish:invoked after examination suite execution finishes.

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.

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 ``);}}

Below are the two various child classes:

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 '');}}

And the second 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 '');}}

Their respective xml files:

& 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;

The concluding testNG xml file:

& 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;

Console Output:

8. ITestListener

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:

  • onStart ():conjure after test class is instantiated and before execution of any testNG method.
  • onTestSuccess ():evoke on the success of a examination
  • onTestFailure (): invoked on the failure of a test
  • onTestSkipped ():stir when a trial is skipped
  • onTestFailedButWithinSuccessPercentage (): invoked whenever a method fails but within the defined success percentage
  • onFinish (): invoke after all exam of a grade are executedThe above-mentioned methods use the argumentITestContext and ITestResult. The ITestContextis a class that contains information about the exam run. TheITestResultis an interface that specify the result of the test.

Now, let & # 8217; s expression at an exemplar showcasing the use of this listener.

Below is a listener family that implements 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 ());}}

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:

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);}}}

Below is the testNG xml file:

& 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;

Console output:

Talk to an Expert

Why use BrowserStack Automate to run TestNG Selenium Tests?

You should run Selenium TestNG Tests on a real device cloud like BrowserStack Automate for below reasons:

  • Realistic Testing Conditions: Real device clouds ply access to a wide spectrum of devices and environments, insure tests reflect actual user weather accurately.
  • Enhanced Security:Maintained with high security standards, real device clouds offer secure, isolated testing environments, minimizing data breach risks.
  • Broad Browser and OS Coverage: Helps identify compatibility issue across diverse browser and operating systems, enhancing user experience.
  • Performance Insights: Real device yield authentic performance data essential for optimize coating responsiveness.
  • Scalability and Accessibility: Facilitates scalable and accessible testing, suitable for distributed team.
  • CI/CD Integration: Integrates swimmingly with CI/CD line for continuous testing and early number catching.
  • Cost-Effectiveness: Although initially more high-priced, it save on long-term expenses related to fixes and support.

Conclusion

  • Listeners play an essential role when contrive an. They make execution smoother, with required actions performed after events are triggered.
  • From taking screenshots when test cases fail, to customizing reports to changing values during run time, TestNG Listeners help to refine and make easier.

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.

Tags
62,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free