What are TestNG Listeners?
As the name suggests, a Listener is something that listens to events and reacts to them. In TestNG, listeners are special interfaces that allow you to modify the behavior of test execution.
TestNG Listeners in Selenium WebDriver are components that monitor the test lifecycle and perform specific actions at different stages of test execution.
In Selenium WebDriver with TestNG, listeners can be used to:
Monitor test execution
Generate logs
Capture screenshots
Create custom reports
Send alerts on test failures
Let's explore the types of listeners and their use cases in this section.
Key Points to Remember
1. Listeners are not constantly active by default. They must be registered before or during test execution.
2. All TestNG listeners implement the marker interface org.testng.ITestNGListener.
3. Listeners can be declared either:
a. At the class level using the @Listeners annotation.
b. At the suite level inside the testng.xml configuration file.
Types of Listeners :
ISuiteListener: To perform some operations when the test suite starts and when all the tests are executed. This interface contains two methods – onStart & onFinish, and provides access tothe test suite object.
ITestListener: To analyze test methods, perform logging. We can also use them to send notifications if any test fails by implementing the onTestFailure(ITestResult result) method.
IAnnotationTransformer: To modify the annotations for any @Test method. Note that we can use this annotation only with TestNG XML configuration.
IAnnotationTransformer2: To modify the annotations for any method other than @Test method. This annotation can be used with TestNG XML configuration only.
IConfigurable: If a test class implements this interface, its run() method will be invoked instead of each configuration method found.
IConfigurationListener: For events related to configuration methods.
IExecutionListener: To monitor when a TestNG run starts and ends.
IHookable: If a test class implements this interface, its run() method will be invoked instead of each @Test method found.
IInvokedMethodListener: A listener that gets invoked before and after a method is invoked by TestNG.
IMethodInterceptor: To alter the list of test methods that TestNG is about to run.
IReporter: Used to generate custom reports after test execution.
Levels of Listener Implementation
Class Level
Use @Listeners annotation to apply listeners to a specific test class.
Suite Level
Declare listeners in the testng.xml file to apply across the entire test suite.
ListenersTest Class
TestClass.java
Testng.xml
Output