Sunday 15 March 2020

TestNG: IExecutionListener: Monitor test starts and ends.

IExecutionListener is used to to monitor when a TestNG run starts and ends.

IExecutionListener provide following methods.

Method
Description
void onExecutionStart()
Invoked before the TestNG run starts.
void onExecutionFinish()
Invoked once all the suites have been run

Find the below working application.

Step 1: Implement IExecutionListener interface

CustomExecutionListener.java
package com.sample.app.tests;

import org.testng.IExecutionListener;

public class CustomExecutionListener implements IExecutionListener{
 public void onExecutionStart() {
  System.out.println("TestNG about to start execution");
 }
 
 public void onExecutionFinish() {
  System.out.println("All the test cases are executed");
 }
}

Step 2: Define test classes.

Test1.java
package com.sample.app.tests;

import org.testng.annotations.Test;

public class Test1 {
 @Test
 public void A() {
  System.out.println("Inside Test1 A");
 }
}

Test2.java
package com.sample.app.tests;

import org.testng.annotations.Test;

public class Test2 {

 @Test
 public void A() {
  System.out.println("Inside Test2 A");
 }
}

Step 3: Define suite. Create ‘execListener.xml’ file in the same package where the test classes are defined.

execListener.xml
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >

<suite name="sanity test suite" time-out="5000">

 <listeners>
  <listener
   class-name="com.sample.app.tests.CustomExecutionListener"></listener>
 </listeners>

 <test name="Demo test app">
  <classes>
   <class name="com.sample.app.tests.Test1"></class>
   <class name="com.sample.app.tests.Test2"></class>
  </classes>
 </test>

</suite>

How to run the suite?
Right click on ‘execListener.xml’ file -> Run As -> TestNG Suite.



You will see below messages in console.

[RemoteTestNG] detected TestNG version 7.0.0
TestNG about to start execution
Inside Test1 A
Inside Test2 A

===============================================
sanity test suite
Total tests run: 2, Passes: 2, Failures: 0, Skips: 0
===============================================

All the test cases are executed



Previous                                                    Next                                                    Home

No comments:

Post a Comment