Listeners for TestNG



  • This listener tracks everything about test cases execution.

  • Requirement is → take screenshots for every failure test cases.

  • If you are not aware of listeners then every time you will be checking whether test case is failed or not. Then writing a code for screen shot. This is not good for maintenance to overcome this we can use listener.

Step 1: create listener class implements it with ITestListener. Try reading name of every method, you will easily understand what that method does its self-explanatory.


Just to explain

Above method which will get executed for every failure of any test cases so we can write any code here which we want to execute for every failure of test case.
Now we can add screen shot code of selenium write here.

Step 2: Modify testng.xml file to add listener entry there. So that whenever our suite runs it initializes listener and it will watch our execution.

listeners in testng xml file

Run above xml and observe output.

Now we will see one live example, it is using data provider.

1) ListenerTest.java


2) DataProviderEx.java


3) CaptureScreenShot.java


4) Testng.xml

Sometimes our test case fails because of setup,network issue, Random browser issues etc not because of product bug. TestNG provides a RetryAnalyzer interface feature using which we can retry a test case multiple times before declaring it as Failed.

As above IRetryAnalyzer has only one method.
i.e : public boolean retry(ITestResult result);

Below is IRetryAnalyzer implementation
Here we are creating maven project and adding dependencies for Retryanalyzer so all the required jars will add in project.

POM.xml


Create a class which implement IRetryAnalyzer interface as below:


In order for TestNG to know about retry analyzer implementation, it provides a retryAnalyzer property in @Test annotation. So below is a small code of how the test configuration would look like:

Create a class which implement IRetryAnalyzer interface as below:

Here we are failing both TC and provides a retryAnalyzer property for only first testcase. So once first TC will fail again it will execute the same TC as per mention in retry limit. Here first time TC fails then it will retry again till retry limit i.e 4 so the same TC will execute 5 times and the result will look like as below :

iretryanalyzer example

List of other testNG listeners (only remember, no need to check example of these)

  • IAnnotationTransformer

  • IAnnotationTransformer2

  • IHookable

  • IInvokedMethodListener

  • IMethodInterceptor

  • IReporter

  • ISuiteListener

  • ITestListener

  • IRetryAnalyzer -- Retry Failed Tests in TestNG