TestNG Listeners in Selenium:

 

  • The listener is defined as the interface which modifies the behavior of the default TestNG.
  • As the name suggests, listeners “listen” for the event defined in the Selenium script and behave accordingly.
  • It is used in selenium by applying listeners interface.
  • TestNG listeners use to create logs in Selenium.
  • TestNG can generate step by step logs with the help of Listeners.
  • It allows customizing TestNG reports or logs with the help of listeners.

 

TestNG provides us below listeners:

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

 

Note: These interfaces are used in selenium to generate logs or customize the testing reports with the help of Step by Step Scenario’s.

 

ITestListener ( I ):

 

When  we use ITestListener:

  • After successfully completing each test.
  • After each failed test.
  • After each test skipped.
  • After the completion of all tests.

 

Methods in ITestListener are following below:

 

 1. OnStart( ):

onStart method is called when any Test starts.

 

2. onTestSuccess( ):

onTestSuccess method is called on the success of any Test.

 

3. onTestFailure( ):

onTestFailure method is called on the failure of any Test.

 

4. onTestSkipped( ):

onTestSkipped method is called on skipped of any Test.

 

5. onTestFailedButWithinSuccessPercentage( ):

method is called each time Test fails but is within success percentage.

 

6. onFinish( ):

onFinish method is called after all Tests are executed.

 

Step 1: Create a simple class and implement ITestListener listener.

 

Step 2: Add all unimplemented methods.

 

Note: Before execute program add Listener class into TestNG.xml file then Run as TestNG Suite to TestNG listeners in Selenium.

Output:

Step 3:  Add listener class into TestNG.xml file.

 

Example: Add listeners into existing TestNG.xml file.