ExtentReports with TestNG via ITestListener. (Session-3)

Generating reports via ITestListener interface is very easy. Here we can record every event.

ITestListener Interface

Listeners are basically keep a track of each event during the program execution. ITestListener provides many pre-defined methods which can be overridden by the programmer to use while automation.

In this blog, we will learn about the below methods which can be easily integrated with ExtentReports.

  1. onTestSuccess(ITestResult): Perform action if @Test is Passed.
  2. onTestFailure(ITestResult): Perform action if @Test is Failed.
  3. onTestSkipped(ITestResult): Perform action if @Test is Skipped.

Override methods in ITestListener Interface

To achieve this we have to first create a Class and which implements the ITestListener. Once implemented the user-defined class will show an error with a red underline. Just mouse hover over the class name and select the “Add unimplemented methods” option.

This will add all the methods in a user-defined class and a developer can define these methods as per the requirement.

Before moving to this section, first will create remaining files in project. You can take reference from previous blog.

Code Example

ClassA.java

Having static object references for ExtentSparkReporter and ExtentReports classes.

import org.testng.annotations.BeforeTest;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;

/**
 * @author ashok.kumar
 *
 */
public class ClassA {
	
	// Declared static to access across multiple Classes.
	static ExtentSparkReporter reporter;
	static ExtentReports logger;
	
	@BeforeTest
	public void reportSetting()
	{
		reporter=new ExtentSparkReporter("Reports\\resultTestNG.html");
		logger=new ExtentReports();
		logger.attachReporter(reporter);
		System.out.println("Report Settings completed.");
	}	
}

ClassB.java

Contains all the @Test methods which will be the test cases in the program. Here we have taken 3 Test cases, and the result would be as mentioned below:

  1. launchBrowserURL(): Result would be Pass.
  2. searchKeyword(): Depends on the above Test and the result would be Fail.
  3. openFirstLink(): Depends on the above Test and the result would be Skip as the above method will fail.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * @author ashok.kumar
 *
 */
public class ClassB{
	
	WebDriver driver;
	
	@Test(description = "To launch a browser and target URL.")
	public void launchBrowserURL()
	{
		System.setProperty("webdriver.chrome.driver", "c:\\chromedriver.exe");
		driver=new ChromeDriver();
		driver.get("https://google.com");
		
		String browserTitle=driver.getTitle();
		Assert.assertEquals(browserTitle, "Google");
	}
	
	@Test(description = "To search a keyword",dependsOnMethods = "launchBrowserURL")
	public void searchKeyword()
	{
		driver.findElement(By.name("q")).sendKeys("Computer"+Keys.ENTER);
		String browserTitle=driver.getTitle();
		Assert.assertEquals(browserTitle, "Computers - Google Search");	
	}
	
	@Test(description="To Open First link.",dependsOnMethods = "searchKeyword")
	public void openFirstLink()
	{	driver.findElement(By.xpath("//a[contains(text(),'Computer')]")).click();
		String browserTitle=driver.getTitle();
		Assert.assertEquals(browserTitle, "Computer");			
	}
}

UserListener.java

Now we have to create user defined listener and override methods from ITestListener Interface.

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

import com.aventstack.extentreports.Status;
/**
 * @author ashok.kumar
 *
 */
public class UserListener implements ITestListener{

	@Override
	public void onTestStart(ITestResult result) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onTestSuccess(ITestResult result) {
		System.out.println("When Test case Passed called from ITestListener");
		String methodName=result.getMethod().getMethodName();
		String description=result.getMethod().getDescription();
		ClassA.logger.createTest(methodName+" "+description)
		.log(Status.PASS,description);
		ClassA.logger.flush();
	}

	@Override
	public void onTestFailure(ITestResult result) {
		System.out.println("When Test case Failed called from ITestListener");
		String methodName=result.getMethod().getMethodName();
		String description=result.getMethod().getDescription();
		Throwable errorMessage=result.getThrowable();
		ClassA.logger.createTest(methodName+" "+description)
		.log(Status.FAIL,errorMessage);
		ClassA.logger.flush();
	}

	@Override
	public void onTestSkipped(ITestResult result) {
		
		System.out.println("When Test Case Skipped called from ITestListener");
		String methodName=result.getMethod().getMethodName();
		String description=result.getMethod().getDescription();
		ClassA.logger.createTest(methodName+" "+description)
		.log(Status.SKIP,"This test case skipped.");
		ClassA.logger.flush();
	}

	@Override
	public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStart(ITestContext context) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onFinish(ITestContext context) {
		// TODO Auto-generated method stub
	}
}

TestNG.xml

Now, as the last step, we have to call the newly created Listener class along with the other classes in our XML file.

This can be easily done by using <listeners> tag in the xml file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="testSuite2">

	<listeners>
             <listener class-name="reporting.UserListener">     </listener>
	</listeners>

	<test name="Test1">
		<classes>
			<class name="reporting.ClassA"></class>
			<class name="reporting.ClassB"></class>
		</classes>
	</test>
</suite> <!-- Suite -->

Result Analysis

In the result we can see all the status Pass, Fail, Skipped.

Result with Skipped test results.

ExtentReports:


Leave a Comment

Your email address will not be published. Required fields are marked *

   YouTube ChannelQuora

            Ashok Kumar is working in an IT Company as a QA Consultant. He has started his career as a Test Trainee in manual testing in August 2010. Then he moves towards the automation testing after 4 years. He started learning JAVA and Selenium by self to get the knowledge of automation.

       While learning these tools and working on multiple projects, he found that sometimes people get stuck in live scenarios in their project and they have to do lots of RnD to get out of it. So he decided to start blogging only for such scenarios, where anyone facing any problem in their project, can ask any question or give a solution or you can say an alternate solution to achieve the goal successfully.

Later on, he observed that some people want to learn Java but they have few questions in their mind like how to start Java, whether we should go for the online or offline course. So he started writing tutorials on Java, Jira, Selenium, Excel etc.