How to Generate Extent Reports in Selenium Webdriver

Generate Extent Reports in Selenium Webdriver: As we all know, Selenium WebDriver does not provide any feature for report generation, So for report generation, we are using JUnit & TestNG with Selenium WebDriver. So, in our previous article, we saw how we can generate a report using TestNG.

Although the TestNG reports provide information like Which steps were executed and what the result is, we still need more customization to that report because it is not more readable and interactive. If we want to make that attractive, we need to put lots of effort into making that attractive.

In that case, we can think about some third-party tools that can provide us with all the features and smoothly implement any automation framework. When I had a solution, I came across a report-generating tool, Extents Reports.

Extents reports offer several advantages over the built-in default reports; those are:

  • Easy To Use
  • Results are displayed in the form of pie charts
  • Provides passed test case percentage
  • Displays test execution time.
  • Environment details can be added in a natural way
  • Screenshots can be attached to the report
  • Test reports can be filtered based on the test results (Pass/Fail/Skip etc.)
  • Filtering stepwise results like info/pass/fail, etc.
  • Categorised report for Regression/Functional etc. testing
  • Test step logs can be added
  • It can be used with JUnit/TestNG.
  • It can be used as a listener for TestNG
  • We can create parallel runs as well. So, a single report can be created for the parallel runs.
  • We can add the configuration to the report.
  • Results from multiple runs can be combined into a single report.

This is one of the most popular Selenium Reporting tools. So, let’s see how we can generate the report using Extents reports in Selenium WebDriver.

Using Extent Reports in Selenium Webdriver:

In Extent Report, we are going to use the below classes:

  • ExtentHtmlReporter
  • ExtentReports class
  • ExtentTest class

ExtentHtmlReporter – The ExtentHtmlReporter creates a rich standalone HTML file.

ExtentReports class: By using this class, we can set the path where our reports need to be stored.

ExtentReports reports = new ExtentReports(“Path of directory”, true/false);

We have passed a boolean value in the above syntax with the path. If the value is true, the existing reports must be overwritten; if the value is false, a new report must be created.

ExtentTest class: With the help of this class, we can generate logs in the report

ExtentTest test = reports.startTest(“TestName”);

The above two classes have some built-in methods used frequently during the implementation of the extent reports. Those methods are:

  • startTest
  • endTest
  • Log
  • flush

startTest and endTest – These two methods are mainly used to execute the preconditions and postconditions of a test case.
Log – This is used for logging the status into the HTML report
Flush – This method erases any previous data on the report and creates a new report.

When we are executing test cases, in that case, the status may be any of the following:

  • Pass
  • Fail
  • Skip
  • Info

So we can use the log method with the above status, we can use it like the below:

test.log(LogStatus.PASS, "Test Passed");
test.log(LogStatus.FAIL, "Test Failed");
test.log(LogStatus.SKIP, "Test Skipped");
test.log(LogStatus.INFO, "Test Info");

Here, the First parameter represents the status, and the second parameter is the message that needs to be printed in the report.

Pre-requisites to Generate Extent Reports:

  • Java Should be installed
  • TestNG should be installed
  • Download Extent Report Jars
  • extent-config.xml – It allows to configure HTML Report

Steps to Follow For Generate Extent Reports:

  • Create a TestNG Project
  • Download the Extent Report Jar File
  • Add the Extent Report Jar Files Into the Project
  • Create A Implemented Class

Java Class:

package myExtentReport;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.*;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.Theme;

public class ExtentReportsClass 
{
   public WebDriver driver;
   public ExtentHtmlReporter htmlReporter;
   public ExtentReports extent;
   public ExtentTest logger;

   @BeforeTest
   public void startReport() 
   {
      htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir") + "/test-output/STExtentReport.html");
      // Create an object of Extent Reports
      extent = new ExtentReports();
      extent.attachReporter(htmlReporter);
      extent.setSystemInfo("Host Name", "SoftwareTesting0");
      extent.setSystemInfo("Environment", "Production");
      extent.setSystemInfo("User Name", "STestngo");
      htmlReporter.config().setDocumentTitle("Title of the Report Comes here ");
      // Name of the report
      htmlReporter.config().setReportName("Name of the Report Comes here ");
      // Dark Theme
      htmlReporter.config().setTheme(Theme.STANDARD);
   }

   //This method is to capture the screenshot and return the path of the screenshot.
   public static String getScreenShot(WebDriver driver, String screenshotName) throws IOException 
   {
      String dateName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
      TakesScreenshot ts = (TakesScreenshot) driver;
      File source = ts.getScreenshotAs(OutputType.FILE);
      // after execution, you could see a folder "FailedTestsScreenshots" under src folder
      String destination = System.getProperty("user.dir") + "/Screenshots/" + screenshotName + dateName + ".png";
      File finalDestination = new File(destination);
      FileUtils.copyFile(source, finalDestination);
      return destination;
   }

   @BeforeMethod
   public void setup()
   {
      System.setProperty("webdriver.chrome.driver","C://AutomationFramework//Drivers//chromedriver.exe");
      driver = new ChromeDriver();
      driver.manage().window().maximize();
      driver.get("https://www.google.com/");
   }

   @Test
   public void verifyTitle() 
   {
      logger = extent.createTest("To verify Google Title");
      Assert.assertEquals(driver.getTitle(),"Google");
   }

   @Test
   public void verifyLogo() 
   {
      logger = extent.createTest("To verify Google Logo");
      boolean img = driver.findElement(By.xpath("//img[@id='hplogo']")).isDisplayed();
      logger.createNode("Image is Present");
      Assert.assertTrue(img);
      logger.createNode("Image is not Present");
      Assert.assertFalse(img);
   }

   @AfterMethod
   public void getResult(ITestResult result) throws Exception
   {
      if(result.getStatus() == ITestResult.FAILURE)
      {
         //MarkupHelper is used to display the output in different colors
         logger.log(Status.FAIL, MarkupHelper.createLabel(result.getName() + " - Test Case Failed", ExtentColor.RED));
         logger.log(Status.FAIL, MarkupHelper.createLabel(result.getThrowable() + " - Test Case Failed", ExtentColor.RED));
         //To capture screenshot path and store the path of the screenshot in the string "screenshotPath"
         //We do pass the path captured by this method in to the extent reports using "logger.addScreenCapture" method.
         //String Scrnshot=TakeScreenshot.captuerScreenshot(driver,"TestCaseFailed");
         String screenshotPath = getScreenShot(driver, result.getName());
         //To add it in the extent report
         logger.fail("Test Case Failed Snapshot is below " + logger.addScreenCaptureFromPath(screenshotPath));
      }
      else if(result.getStatus() == ITestResult.SKIP)
      {
         logger.log(Status.SKIP, MarkupHelper.createLabel(result.getName() + " - Test Case Skipped", ExtentColor.ORANGE));
      }
      else if(result.getStatus() == ITestResult.SUCCESS)
      {
         logger.log(Status.PASS, MarkupHelper.createLabel(result.getName()+" Test Case PASSED", ExtentColor.GREEN));
      }
      driver.quit();
   }

   @AfterTest
   public void endReport() 
   {
      extent.flush();
   }
}

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

2 thoughts on “How to Generate Extent Reports in Selenium Webdriver”

  1. Hi

    This is quiet nice compare to others that I have seen, am new to this assuming I want the screenshot to be stored in folder. How do I go about doing it
    //To capture screenshot path and store the path of the screenshot in the string “screenshotPath”
    //We do pass the path captured by this method in to the extent reports using “logger.addScreenCapture” method.
    //String Scrnshot=TakeScreenshot.captuerScreenshot(driver,”TestCaseFailed”);
    String screenshotPath = getScreenShot(driver, result.getName());
    //To add it in the extent report

    Reply

Leave a Comment