ExtentReports with TestNG (AfterMethod annotation). (Session-2)

ExtentReports can be integrated with TestNG easily. All the processes and methods will remain the same as we learned in Session-1.

ExtentReports with TestNG

We need to just take care of few things while implementing the ExtentReports in TestNG, rest all the syntax and logic will remain the same.

Here we are taking one live demo. Below is the structure of the program.

  1. ClassA: Used to create and initialize the objects of ExtentSparkReporter and ExtentReports.
    • Both the objects should be declared static
    • Both objects should be Class Level instances.
    • Add @BeforeTest annotation to initialize these instances.
  2. ClassB: This method will contain the test cases and test results.
    • Declared WebDriver object at the class level.
    • Create test cases via @Test annotation
      1. launchBrowserURL(): To initialize the WebDriver object and launch the target URL
      2. searchKeyword(): To search a keyword on the google search engine.
      3. openFirstLink(): To open the first link on the search result page.
    • Add @AfterMethod annotation to record the result.
      1. recordResult(ITestResult): method to record the result of each test method.
      2. ITestResult: is an interface that is used to access the test case result status, test case name, test case description, etc. Below are a few important methods of ITestResult:
        • getMethod().getMethodName(): Extract the last executed method name.
        • getMethod().getDescription(): Extract the last executed method description.
        • getThrowable(): Extract the exception if the test case result is FAIL.
        • getStatus(): To extract the test case result status(Pass/Fail/Skip).
  3. TestNG.xml: To run the program as TestNG.

Note: As we know that @AfterTest annotation will not suppose execute for Skipped methods. So, we can keep track of the only Pass or Fail test cases via the ExtentReports. Will learn later how to get rid of this.

Code Example


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;
	public void reportSetting()
		reporter=new ExtentSparkReporter("Reports\\resultTestNG.html");
		logger=new ExtentReports();
		System.out.println("Report Settings completed.");


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.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import com.aventstack.extentreports.Status;

 * @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();
		String browserTitle=driver.getTitle();
		Assert.assertEquals(browserTitle, "Google");
	@Test(description = "To search a keyword",dependsOnMethods = "launchBrowserURL")
	public void searchKeyword()
		String browserTitle=driver.getTitle();
		Assert.assertEquals(browserTitle, "Computer - Google Search");	
	@Test(description="To Open First link.",dependsOnMethods = "searchKeyword")
	public void openFirstLink()
		String browserTitle=driver.getTitle();
		Assert.assertEquals(browserTitle, "Computer");			
	@AfterMethod(alwaysRun = true)
	public void recordResult(ITestResult testStatus)
		// Extract last executed method name
		String methodName=testStatus.getMethod().getMethodName();
		// Extract last executed method description
		String methodDetails=testStatus.getMethod().getDescription();
		// Get the exception if the result is Failed.
		Throwable methodInfo=testStatus.getThrowable();
		// Skip status won't be tracked as @AfterMethod not supposed to run for Skipped Methods.
		System.out.println("Result Analysis Started.");
			ClassA.logger.createTest(methodName+" "+methodDetails).log(Status.PASS, methodDetails);
			ClassA.logger.createTest(methodName+" "+methodDetails).log(Status.FAIL, methodInfo);
		System.out.println("Result Generated.");


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

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

Result Analysis

Result Analysis.


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.