How to Generate Extent Reports in Selenium

Understand Extent Reports in Selenium. Use AI-powered Reports & Analytics dashboard for detailed reporting of Selenium Tests

Get Started free
Guide Banner Image
Home Guide How to Generate Extent Reports in Selenium

How to Generate Extent Reports in Selenium

Tracking and analyzing Selenium test results can be difficult without clear reports, slowing down issue identification and debugging. A structured reporting solution provides detailed insights with essential test data, improving test management and speeding up troubleshooting.

Overview

Extent Reports in Selenium are a popular reporting tool used to generate detailed and interactive test execution reports with customizable features, such as logs, screenshots, and test results.

Key Characteristics of Extent Reports in Selenium:

  • Customizable Reports: Allows users to customize the look and feel of the reports, including test status and details.
  • Interactive UI: Provides an interactive and user-friendly interface to view test execution results.
  • Test Status Tracking: Displays detailed information on passed, failed, and skipped tests.
  • Logs and Screenshots: Supports adding logs and screenshots for better test debugging and analysis.
  • Real-Time Updates: Provides real-time reporting during test execution for quick feedback.
  • Supports Multiple Formats: Reports can be generated in HTML, PDF, or other formats for easy sharing and archiving.

This article explores Extent Reports, how to use them in Selenium, generate reports with NUnit, capture screenshots, and the benefits of integrating Extent Reports in testing.

What are Extent Reports?

Extent Reports is an open-source reporting library useful for test automation. It can be easily integrated with major testing frameworks like JUnit, NUnit, TestNG, etc. These reports are HTML documents that depict results as pie charts. They also allow the generation of custom logs, snapshots, and other customized details.

Once an automated test script runs successfully, testers need to generate a test execution report. While TestNG does provide a default report, they do not provide the details.

Note: BrowserStack is now the first cloud test automation platform to announce complete support for Selenium 4, and it’s BiDi APIs. Learn More.

Using Extent Reports in Selenium

Extent Reports in Selenium contain two major, frequently used classes:

  • ExtentReports class
  • ExtentTest class

Syntax

ExtentReports reports = new ExtentReports("Path of directory to store the resultant HTML file", true/false);

ExtentTest test = reports.startTest("TestName");

The ExtentReports class generates HTML reports based on a path specified by the tester. Based on the Boolean flag, the existing report has to be overwritten or a new report must be generated. ‘True’ is the default value, meaning that all existing data will be overwritten.

The ExtentTest class logs test steps onto the previously generated HTML report.

Both classes can be used with the following built-in methods:

  • startTest: Executes preconditions of a test case
  • endTest: Executes postconditions of a test case
  • Log: Logs the status of each test step onto the HTML report being generated
  • Flush: Erases any previous data on a relevant report and creates a whole new report

A Test Status can be indicated by the following values:

  • PASS
  • FAIL
  • SKIP
  • INFO

Syntax

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

The Log method takes into account two parameters, the first being the test status and the second being the message to be printed onto the generated report.

By integrating Extent Reports with Selenium, you can streamline test reporting and gain deeper insights into your test executions.

For a more powerful and scalable testing experience, BrowserStack Automate offers a cloud platform that runs Selenium tests on real browsers and devices, further enhancing the quality of your reports.

BrowserStack Automate Banner

Run Selenium Tests on Real Browsers

How to generate Extent Reports

The following steps will guide you through the process of setting up and generating detailed reports for your Selenium tests.

  1. Import the JAR file : extentreports-java-2.41.2.jar . After downloading the ZIP file, extract its contents into a folder.
  2. Add the JAR files to the project build path with the option Build Path -> Configure Build Path.
  3. Create a new JAVA class for Extent Reports with the code below.
package com.browserstack.demo;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class ExtentDemo {
static ExtentTest test;
static ExtentReports report;
@BeforeClass
public static void startTest()
{
report = new ExtentReports(System.getProperty("user.dir")+"ExtentReportResults.html");
test = report.startTest("ExtentDemo");
}
@Test
public void extentReportsDemo()
{
System.setProperty("webdriver.chrome.driver", "D:SubmittalExchange_TFSQAAutomation3rdpartychromechromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.co.in");
if(driver.getTitle().equals("Google"))
{
test.log(LogStatus.PASS, "Navigated to the specified URL");
}
else
{
test.log(LogStatus.FAIL, "Test Failed");
}
}
@AfterClass
public static void endTest()
{
report.endTest(test);
report.flush();
}
}

Test execution commences with the startTest method. It also initializes the Extent Reports object. Any valid user-defined path can be the parameter passed onto the Extent Reports object.

@Test: This class automates the following actions:

  • Open Chrome browser with the url https://www.google.com
  • After the page opens, validate page title with the expected
  • Log the test case status as PASS/FAIL using the log method explained before

@AfterClass: Executes postconditions of the test case – ending the test (using endTest method) and flushing the report.

Note: Don’t forget to use the flush() method, since the report will not be generated otherwise.

Talk to an Expert

How to generate Extent Reports in Selenium using NUnit

The following steps outline how to set up and generate detailed reports for your NUnit-based Selenium tests.

Using SetupFixture

[SetUpFixture]
public abstract class Base
{
protected ExtentReports _extent;
protected ExtentTest _test;

[OneTimeSetUp]
protected void Setup()
{
var dir = TestContext.CurrentContext.TestDirectory + "\\";
var fileName = this.GetType().ToString() + ".html";
var htmlReporter = new ExtentHtmlReporter(dir + fileName);

_extent = new ExtentReports();
_extent.AttachReporter(htmlReporter);
}

[OneTimeTearDown]
protected void TearDown()
{
_extent.Flush();
}

[TestFixture]
public class TestInitializeWithNullValues : Base
{
[Test]
public void TestNameNull()
{
Assert.Throws(() => testNameNull());
}
}

[SetUp]
public void BeforeTest()
{
_test = _extent.CreateTest(TestContext.CurrentContext.Test.Name);
}

[TearDown]
public void AfterTest()
{
var status = TestContext.CurrentContext.Result.Outcome.Status;
var stacktrace = string.IsNullOrEmpty(TestContext.CurrentContext.Result.StackTrace)
? ""
: string.Format("{0}", TestContext.CurrentContext.Result.StackTrace);
Status logstatus;

switch (status)
{
case TestStatus.Failed:
logstatus = Status.Fail;
break;
case TestStatus.Inconclusive:
logstatus = Status.Warning;
break;
case TestStatus.Skipped:
logstatus = Status.Skip;
break;
default:
logstatus = Status.Pass;
break;
}

_test.Log(logstatus, "Test ended with " + logstatus + stacktrace);
_extent.Flush();
}
}

Interested in picking up Selenium automation? Get access to real device cloud for a hands-on learning experience, and master the fundamentals of software testing with BrowserStack Test University. Sign Up for Free.

BrowserStack Test Observability Banner 1

How to capture screenshots in Extent Report

By capturing screenshots, testers can better identify what went wrong when the software acted erroneously during a test. Capture screenshots only when a test fails, since they consume a lot of memory.

Try capturing screenshots with the code below

test.log(LogStatus.FAIL,test.addScreenCapture(capture(driver))+ "Test Failed");
public static String capture(WebDriver driver) throws IOException {
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File Dest = new File("src/../BStackImages/" + System.currentTimeMillis()
+ ".png");
String errflpath = Dest.getAbsolutePath();
FileUtils.copyFile(scrFile, Dest);
return errflpath;
}

getScreenShotAs(): Captures screenshot of the current WebDriver instance and stores it in different output forms.

File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

This method returns a file object to be stored onto a file variable. Casting the web driver instance to Take Screenshot is necessary to use the method.

File Dest = new File("src/../BStackImages/" + System.currentTimeMillis()+ ".png");

This statement creates a folder named ‘BStackImages’ within the ‘src’ folder and stores the file name as the current system time.

String errflpath = Dest.getAbsolutePath();
FileUtils.copyFile(scrFile, Dest);
returnerrflpath;

These statements copy all error images to the destination folder.

Use the log method because it uses the addScreenCapture method of Extent Test class to get a screenshot and add it to the Extent Report.

test.log(LogStatus.FAIL,test.addScreenCapture(capture(driver))+ "Test Failed");

Benefits of using Extent Reports

Using Extent Reports in Selenium offers several advantages, from enhanced visibility into test execution to easy integration of logs and screenshots, improving test management and debugging. Some of the primary benefits include:

  • They can be integrated with TestNG and JUnit
  • If required, screenshots can be captured and displayed for each step in a test
  • They allow testers to track multiple test case runs in a single test suite
  • They show the time needed for test execution
  • They can be customized to graphically represent each step in a test.

Conclusion

Try using the code defined above to generate Extent Reports. By doing so, users can offer themselves and their teams, a more extensive and insightful perspective on the success or failure of their automated Selenium testing. By accessing the greater detail provided by Extent Reports, testers can be more effective when it comes to debugging software quickly.

For an enhanced testing experience, leverage BrowserStack Automate, which offers cloud-based Selenium testing on 3500+ real browsers and devices. With features like parallel test execution, instant feedback, and seamless integration with CI/CD pipelines, BrowserStack allows you to scale your automation efforts and ensure cross-browser compatibility in real-user conditions.

Tags
Automation Testing Selenium Selenium Webdriver

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord