TestNG Listeners With Examples

TestNG Listeners are used to inspect and modify the testing behavior. TestNG listeners always extend org.testng.ITestNGListener marker interface. TestNG listeners can be defined for a test class using org.testng.annotations.Listeners annotation.

TestNG Listeners

There are many listeners interfaces provided by TestNG. They all extend org.testng.ITestNGListener interface.

TestNG-Listeners

Let’s look at some of the important TestNG listeners.

  1. ISuiteListener: We can use this test suite listener to perform some operations when test suite starts and when all the tests are executed. This interface contains two methods – onStart(ISuite suite) and onFinish(ISuite suite) and provides access to test suite object.
  2. ITestListener: We can use this listener to analyze test methods, perform logging. We can also use them to send notifications if any test fails by implementing onTestFailure(ITestResult result) method.
  3. IAnnotationTransformer: We can implement this interface to modify the annotations for any @Test method. Note that we can use this annotation only with TestNG XML configuration.
  4. IAnnotationTransformer2: We can implement this interface to modify the annotations for any method other than @Test method.This annotation can be used with TestNG XML configuration only.
  5. IConfigurable: If a test class implements this interface, its run() method will be invoked instead of each configuration method found.
  6. IConfigurationListener: Listener interface for events related to configuration methods.
  7. IExecutionListener: This listener is used to monitor when a TestNG run starts and ends.
  8. IHookable: If a test class implements this interface, its run() method will be invoked instead of each @Test method found.
  9. IInvokedMethodListener: A listener that gets invoked before and after a method is invoked by TestNG.
  10. IMethodInterceptor: This class is used to alter the list of test methods that TestNG is about to run.
  11. IReporter: This interface can be implemented by clients to generate a report.

TestNG Listener Example

Let’s create a simple TestNG test class, then we will implement few listeners and add it to the class.

When we run above as TestNG test, we get the following output in the console.

ISuiteListener Example

Here is a simple implementation of ISuiteListener interface.

ITestListener Example

Here is a simple implementation of ITestListener interface.

Now modify the Test3 class by adding Listeners to its class definition.

When we run the class again as TestNG test, we get following output.

Summary

TestNG listeners are very powerful in monitoring the test suite and test cases. Some of them can be used to alter the testing behavior at runtime.

By admin

Leave a Reply

%d bloggers like this: