Know about Extent Reports in Selenium

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

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

How to Generate Extent Reports in Selenium

Shreya Bose, Technical Content Writer at BrowserStack -

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.

Incase, one would want to run selenium tests on a real device infrastructure, rather than an on-premise device lab. Try BrowserStack for free.

Run Selenium Tests on Real Browsers

How to generate Extent Reports

  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

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();
}
}

Source

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

  • 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.

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.

Try Selenium Testing for Free

Tags
Automation Testing Selenium Selenium Webdriver

Featured Articles

5 Selenium tricks to make your life easier

Learn Selenium with Java to run Automated Tests

Automation Tests on Real Devices & Browsers

Seamlessly Run Automation Tests on 3500+ real Devices & Browsers