Extent Reports – Screenshots of Failed Test Cases in Extent Reports

Insert Screenshots of a Failed Test Cases in Extent Reports:

In this post, we see how to add Screenshots in Extent Reports – Selenium WebDriver.

Check this post for Latest Version of Extent Reports.

Pre-requisites to Insert Screenshots in Extent Reports:

  1. Java should be installed (Link to Install and setup Java )
  2. TestNG should be installed
  3. Extent Report Jars (Version 2.41.2) – Download
  4. extent-config.xml – It allows to configure HTML Report

Steps To Generate Extent Reports:

  1. Firstly, create a TestNG project in eclipse
  2. Now download extent library files from the following link:  http://extentreports.com/
  3. Add the downloaded library files in your project
  4. Add Selenium WebDriver Jars
  5. Create a java class say ‘ExtentReportsClass’ and add following code to it

NOTE: In this post, I am not explaining everything. In the earlier post (i.e., Generate ExtentReports ), I have mentioned detailed explanation. In this I just explain how to capture screenshot and pass it to the extent reports.

Below mentioned method is to capture the screenshot and returns the path of the screenshot.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Creating a method getScreenshot and passing two parameters
//driver and screenshotName
public static String getScreenshot(WebDriver driver, String screenshotName) throws Exception {
                //below line is just to append the date format with the screenshot name to avoid duplicate names
                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”) + “/FailedTestsScreenshots/”+screenshotName+dateName+“.png”;
File finalDestination = new File(destination);
FileUtils.copyFile(source, finalDestination);
                //Returns the captured file path
return destination;
}

Same code (getScreenshot method) I have placed in the below TestNG Class. You could also place this code in your utilities function class.

If you are a beginner and wants to know how to capture screenshot then check this post on how to capture screenshot in Selenium and this post to capture full page screenshot using aShot

Program to insert captured screenshots in extent reports:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package softwareTestingMaterial;
 
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.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.SkipException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
 
 
//It is possible to attach screenshots. To add a screen-shot, simply call addScreenCapture.
//This method returns the HTML with  tag which can be used anywhere in the log details.
public class ExtentReportsClass{
ExtentReports extent;
ExtentTest logger;
WebDriver driver;
@BeforeTest
public void startReport(){
//ExtentReports(String filePath,Boolean replaceExisting)
//filepath – path of the file, in .htm or .html format – path where your report needs to generate.
//replaceExisting – Setting to overwrite (TRUE) the existing file or append to it
//True (default): the file will be replaced with brand new markup, and all existing data will be lost. Use this option to create a brand new report
//False: existing data will remain, new tests will be appended to the existing report. If the the supplied path does not exist, a new file will be created.
extent = new ExtentReports (System.getProperty(“user.dir”) +“/test-output/STMExtentReport.html”, true);
//extent.addSystemInfo(“Environment”,”Environment Name”)
extent
                .addSystemInfo(“Host Name”, “SoftwareTestingMaterial”)
                .addSystemInfo(“Environment”, “Automation Testing”)
                .addSystemInfo(“User Name”, “Rajkumar SM”);
                //loading the external xml file (i.e., extent-config.xml) which was placed under the base directory
                //You could find the xml file below. Create xml file in your project and copy past the code mentioned below
                extent.loadConfig(new File(System.getProperty(“user.dir”)+“\\extent-config.xml”));
}
 
        //This method is to capture the screenshot and return the path of the screenshot.
public static String getScreenhot(WebDriver driver, String screenshotName) throws Exception {
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”) + “/FailedTestsScreenshots/”+screenshotName+dateName+“.png”;
File finalDestination = new File(destination);
FileUtils.copyFile(source, finalDestination);
return destination;
}
@Test
public void passTest(){
//extent.startTest(“TestCaseName”, “Description”)
//TestCaseName – Name of the test
//Description – Description of the test
//Starting test
logger = extent.startTest(“passTest”);
Assert.assertTrue(true);
//To generate the log when the test case is passed
logger.log(LogStatus.PASS, “Test Case Passed is passTest”);
}
@Test
public void failTest(){
                //My intention is to fail this method
                //If this method fails, then it goes to the @AfterMethod and calls the getScreenshot method and captures a screenshot and place it in the extent reports
logger = extent.startTest(“failTest”);
System.setProperty(“webdriver.gecko.driver”,“D://Selenium//Drivers//geckodriver.exe”);
driver = new FirefoxDriver();
driver.get(“https://www.softwaretestingmaterial.com”);
String currentURL = driver.getCurrentUrl();
Assert.assertEquals(currentURL, “NoTitle”);
logger.log(LogStatus.PASS, “Test Case (failTest) Status is passed”);
}
@Test
public void skipTest(){
logger = extent.startTest(“skipTest”);
throw new SkipException(“Skipping – This is not ready for testing “);
}
@AfterMethod
public void getResult(ITestResult result) throws IOException{
if(result.getStatus() == ITestResult.FAILURE){
logger.log(LogStatus.FAIL, “Test Case Failed is “+result.getName());
logger.log(LogStatus.FAIL, “Test Case Failed is “+result.getThrowable());
//To capture screenshot path and store the path of the screenshot in the string “screenshotPath”
                        //We do pass the path captured by this mehtod in to the extent reports using “logger.addScreenCapture” method.
                        String screenshotPath = ExtentReportsClass.getScreenshot(driver, result.getName());
//To add it in the extent report
logger.log(LogStatus.FAIL, logger.addScreenCapture(screenshotPath));
}else if(result.getStatus() == ITestResult.SKIP){
logger.log(LogStatus.SKIP, “Test Case Skipped is “+result.getName());
}
// ending test
//endTest(logger) : It ends the current test and prepares to create HTML report
extent.endTest(logger);
}
@AfterTest
public void endReport(){
// writing everything to document
//flush() – to write or update test information to your report.
                extent.flush();
                //Call close() at the very end of your session to clear all resources.
                //If any of your test ended abruptly causing any side-affects (not all logs sent to ExtentReports, information missing), this method will ensure that the test is still appended to the report with a warning message.
                //You should call close() only once, at the very end (in @AfterSuite for example) as it closes the underlying stream.
                //Once this method is called, calling any Extent method will throw an error.
                //close() – To close all the operation
                extent.close();
    }
}

extent-config.xml: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?xml version=“1.0” encoding=“UTF-8”?>
<extentreports>
  <configuration>
    <! report theme >
    <! standard, dark >
    <theme>standard</theme>
  
    <! document encoding >
    <! defaults to UTF8 >
    <encoding>UTF8</encoding>
    
    <! protocol for script and stylesheets >
    <! defaults to https >
    <protocol>https</protocol>
    
    <! title of the document >
    <documentTitle>ExtentReports 2.0</documentTitle>
    
    <! report name displayed at topnav >
    <reportName></reportName>
    
    <! report headline displayed at topnav, after reportHeadline >
    <reportHeadline>Automation Report</reportHeadline>
    
    <! global date format override >
    <! defaults to yyyyMMdd >
    <dateFormat>yyyyMMdd</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>

By using this external XML file (extent-config.xml), we could change the details such as Report Theme (either standard or dark), Report Title, Document Title etc.,

We use extent object and use loadConfig() method to load this xml file.

Refresh the project after execution of above ExtentReportsClass.java file. You could find an HTML file named “STMExtentReport.html” in your test-output folder. Copy the location of the STMExtentReport.html file and open it by using any browser. You could see a beautiful high rich HTML reports as shown below.

Extent Report – Test Summary Report Which Contains Screenshot of a Failed Test Case:

This way we could add screenshots of a failed test cases in extent reports.

You could also find introduction of extentreports by clicking on this link