Using Listeners
In this topic, we will see the list of TestNG Listeners.
We'll cover the following
TestNG listeners #
There are several interfaces that allow us to change the behavior of TestNG at runtime:
IAlterSuiteListener
- on implementing this interface, we have methodalter
to alter the test suiteIAnnotationTransformer
- on implementing this interface, we can alter@Test
,@DataProvider
,@Factory
, @Listener annotationsIClassListener
- on implementing this interface, we can callonBeforeClass
andonAfterClass
IConfigurable
- on implementing the interface,run
method will be invoked instead of each configuration method foundIConfigurationListener
- on implementing this interface, we can call methodsonConfigurationSuccess
,onConfigurationFailure
,onConfigurationSkip
andbeforeConfiguration
IDataProviderListener
- methodbeforeDataProviderExecution
andafterDataProviderExecution
IExecutionListener
-onExecutionStart
andonExecutionFinish
IHookable
- this method has a methodrun
and on implementing,run
method will be called instead of@Test
methodIInvokedMethodListener
- on implementing this interface, we have methodbeforeInvocation
,afterInvocation
,beforeInvocation
,afterInvocation
that gets invoked before and after a method is invoked by TestNG, irrespective of whether they pass/fail or gets skippedIMethodInterceptor
- on implementing the interface, we can call intercept to alter the list of test methods that TestNG is about to runIReporter
- on implementing the interface, we have methodgenerateReport
to create custom reportsISuiteListener
- on implementing the interface, we can callonStart
andonFinish
ITestListener
- on implementing the interface, we have methodsonTestStart
,onTestSuccess
,onTestFailure
,onTestSkipped
,onTestFailedButWithinSuccessPercentage
,onTestFailedWithTimeout
,onStart
,onFinish
Declaring listeners #
In testng.xml #
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Sample Test Suite" parallel="tests" thread-count="5">
<listeners>
<listener class-name="com.example.SampleTestListener" />
</listeners>
<test name="Sample Test">
...
</test>
</suite>
Listeners can be configured for the entire test suite in testng.xml like above. Under <listeners>, multiple <listener> can be added.
In TestClass #
@Listeners( { com.example.SampleTestListener.class } )
public class TestClass {
....
}
Listeners can be configured only for certain test classes like the above code snippet by adding @Listeners({ ListenerA.class, ListenerB.class, ...})
at the class level.
That is how listeners work with TestNG. In the next lesson, you will study how to restart a failed test.
Get hands-on with 1400+ tech skills courses.