Cucumber - Extent Reports

Cucumber - Extent Reports

What is Extent Reports

Extent Report is an HTML reporting library for Selenium WebDriver for Java which is to a great degree simple to use and makes excellent execution reports.

Procedure to integrate Cucumber Framework with Extent Report:- Below mentioned are the steps to integrate cucumber with extent reports Step 1: Add below-mentioned dependencies to pom.xml

<!-- https://mvnrepository.com/artifact/com.aventstack/extentreports -->

<dependency>

    <groupId>com.aventstack</groupId>

    <artifactId>extentreports</artifactId>

    <version>3.1.5</version>

    <scope>provided</scope>

</dependency>

<!-- https://mvnrepository.com/artifact/com.vimalselvam/cucumber-extentsreport -->

<dependency>

    <groupId>com.vimalselvam</groupId>

    <artifactId>cucumber-extentsreport</artifactId>

    <version>3.0.2</version>

</dependency>

And Do Maven Clean and Maven Install, Now these jars are associated with your project you can verify the same by navigating to Build Path.

Step 2: Create a New File and name it as extent-config.xml, In this config file you can set many elements, which are described in this file.

This file will be used for customizing your report like passing report Name, title name, etc. Please check the sample file here

<?xml version="1.0" encoding="UTF-8"?>
<extentreports>
  <configuration>
    <!-- report theme --> <!-- standard, dark -->
    <theme>standard</theme>

    <!-- document encoding -->  <!-- defaults to UTF-8 -->
    <encoding>UTF-8</encoding>

    <!-- protocol for script and stylesheets -->   <!-- defaults to https -->
    <protocol>https</protocol>

    <!-- title of the document -->
    <documentTitle>BDD Cucumber Framework Reports</documentTitle>

    <!-- report name - displayed at top-nav -->
    <reportName>Android - Cucumber Report</reportName>

    <!-- global date format override -->  <!-- defaults to yyyy-MM-dd -->
    <dateFormat>yyyy-MM-dd</dateFormat>

    <!-- global time format override -->   <!-- defaults to HH:mm:ss -->
    <timeFormat>HH:mm:ss</timeFormat>

    <!-- custom javascript -->
    <scripts>
      <![CDATA[
        $(document).ready(function() {

        });
      ]]>
    </scripts>

    <!-- custom styles -->
    <styles>
      <![CDATA[

      ]]>
    </styles>
  </configuration>
</extentreports>

Step 3: Read the extent-config file name

Make an entry for the Path of the config in the Configuration.properties file.

Below is the sample:-

reportConfigPath=/Users/path/to/the/file/extent-config.xml

Write a java method to read this config file, below attached is the class reading config file.

package Driver;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class ConfigFileReader {



public String getReportConfigPath(){
    Properties prop = new Properties();
    InputStream input = null;
    try
    {
        prop.load(getClass().getClassLoader().getResourceAsStream("/Users/path/to/the/PropertyFiles/Configuration.properties"));
        String reportConfigPath = prop.getProperty("reportConfigPath");
        if(reportConfigPath!= null) return reportConfigPath;
        else throw new RuntimeException("Report Config Path not specified in the Configuration.properties file for the Key:reportConfigPath");        

    }
    catch (IOException io) {
        io.printStackTrace();
    }finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }    
    return null;

}
}

Step 4: Modify Test Runner to implement cucumber extent report.

Below attached is the Modified Runner report to read the cucumber file.

package Driver;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;

import com.cucumber.listener.ExtentProperties;
import com.cucumber.listener.Reporter;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;




@RunWith(Cucumber.class)
@CucumberOptions(
plugin = {"com.cucumber.listener.ExtentCucumberFormatter:"},        
features = {"/Users/path/to/the/file/feature"},
tags= {"@Notes"},
monochrome = true
 )
public class Runner {

    @BeforeClass
    public static void setup() {
        String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
        ExtentProperties extentProperties = ExtentProperties.INSTANCE;
        extentProperties.setReportPath("cucumber-reports/"+timeStamp.replace(":","_").replace(".","_")+".html");
    }


    @AfterClass
    public static void writeExtentReport() {

        Reporter.loadXMLConfig(new File("/Users/path/to/the/file/extent-config.xml"));
        Reporter.setSystemInfo("User Name", System.getProperty("user.name"));
        Reporter.setSystemInfo("Time Zone", System.getProperty("user.timezone"));
      }
    }

After the modification you can run Runner class as junit test.

Add Logging to your Reports

User can add logs at any step and those logs will be captured and attached to the corresponding step. The log should be added as follows:

Reporter.addStepLog(“Step Log message goes here”);

In case any log to be added at the scenario level, the following can be done:

Reporter.addScenarioLog(“Scenario Log message goes here”);

It's a static class, so feel free to use this Reporter class to anywhere in the project.

Note:- Reporter is the static class, it can be used anywhere in the project.

Add Screenshot for Failed Scenario:

we can also add a screenshot to a step when a scenario is failed.

Below mentioned file will have the code to capture the screenshot.

package Driver;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

import com.cucumber.listener.Reporter;
import com.google.common.io.Files;

import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;


public class BaseTest extends desiredCapabilities {



@Before
public void beforeHookfunction() throws MalformedURLException, InterruptedException{

    Reporter.assignAuthor("assignAuthor");

         //BrowserStack();
        SetDesiredCapabilities();
    }

    @After(order = 0)
    public void afterHookfunction() {
        System.out.println("test completed");
        driver.quit();

    }

    @After(order = 1)
    public void afterScenario(Scenario scenario) {
        if (scenario.isFailed()) {
            String screenshotName = scenario.getName().replaceAll(" ", "_");
            try {
                //This takes a screenshot from the driver at save it to the specified location
                //File sourcePath = ((TakesScreenshot) testContext.getWebDriverManager().getDriver()).getScreenshotAs(OutputType.FILE);

                TakesScreenshot scrShot =((TakesScreenshot)driver);
                 File sourcePath = scrShot.getScreenshotAs(OutputType.FILE);

                //Building up the destination path for the screenshot to save
                //Also make sure to create a folder 'screenshots' with in the cucumber-report folder
                File destinationPath = new File(System.getProperty("user.dir") + "/cucumber-reports/screenshots/" + screenshotName + ".png");

                //Copy taken screenshot from source location to destination location
                Files.copy(sourcePath, destinationPath);   

                //This attach the specified screenshot to the test
                Reporter.addScreenCaptureFromPath(destinationPath.toString());
            } catch (IOException e) {
            } 
        }
    }

}

Report Generation:

Reports will be generated and in the form of date_time.html format, and all the historical reports will be maintained. Below mentioned is the code to save the execution report every time with a different name.

  public static void Reportsetup() {
     String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

     ExtentProperties extentProperties = ExtentProperties.INSTANCE;

     extentProperties.setReportPath("target/cucumber-reports/"+timeStamp.replace(":","_").replace(".","_")+".html");

 }