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.
Pre-requisites to Insert Screenshots in Extent Reports:
- Java should be installed (Link to Install and setup Java )
- TestNG should be installed
- Extent Report Jars (Version 2.41.2) – Download
- extent-config.xml – It allows to configure HTML Report
Steps To Generate Extent Reports:
- Firstly, create a TestNG project in eclipse
- Now download extent library files from the following link: http://extentreports.com/
- Add the downloaded library files in your project
- Add Selenium WebDriver Jars
- 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.
//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:
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:
<?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>ExtentReports 2.0</documentTitle> <!-- report name - displayed at top-nav --> <reportName></reportName> <!-- report headline - displayed at top-nav, after reportHeadline --> <reportHeadline>Automation Report</reportHeadline> <!-- 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>
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
Thanks for the superb post on capture screenshot in extent reports.
Hi,
I added the same code but Image is not attached to the report. Image displayed as a line.
By Looking in to my Code can you please help me where is the error.
I am using Latest version Extentreports-3.1.1.jar
public static WebDriver driver;
public static WebDriverWait wait;
public static Properties sprops = new Properties();
public static Properties aprops = new Properties();
public String ScrPath = System.getProperty(“user.dir”);
public File SharedRepofile = new File(ScrPath+”\\Repositories\\SharedRepo.properties”);
public FileInputStream SharedRepoInputFile;
public FileInputStream AppRepoInputFile;
public String ErrScPath = System.getProperty(“user.dir”)+”\\ErrorScreenshots\\”;
public String CaptureScreenShot(String screenshotname) throws Exception{
DateFormat DF = new SimpleDateFormat(“dd-MM-yyyy_HHmmss”);
Date D = new Date();
String time = DF.format(D);
TakesScreenshot ts = (TakesScreenshot)driver;
File Source = ts.getScreenshotAs(OutputType.FILE);
String dest = ErrScPath + screenshotname+”_”+time+”.png”;
File destination = new File(dest);
FileUtils.copyFile(Source, destination);
return dest;
}
@BeforeTest()
public void beforeTest(String Browser, String DataFile, String AppRepofile ) throws Exception {
if (Browser.equalsIgnoreCase(“Chrome”)) {
ChromeOptions options = new ChromeOptions();
options.addArguments(“test-type”);
options.addArguments(“disable-popup-blocking”);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
System.setProperty(“webdriver.chrome.driver”, “D:\\lib\\chromedriver.exe”);
driver = new ChromeDriver();
}
else if(Browser.equalsIgnoreCase(“IE”)){
System.setProperty(“webdriver.ie.driver”, “D:\\lib\\IEDriverServer.exe”);
driver = new InternetExplorerDriver();
}
else if(Browser.equalsIgnoreCase(“Firefox”)) {
System.setProperty(“webdriver.gecko.driver”, “D:\\lib\\geckodriver.exe”);
driver = new FirefoxDriver();
}
Capabilities cap = ((RemoteWebDriver)driver).getCapabilities();
String OS = System.getProperty(“os.name”);
String BrowserName = cap.getBrowserName().toLowerCase();
String Version = cap.getVersion();
HtmlReporter = new ExtentHtmlReporter(System.getProperty(“user.dir”)+”\\CustomReport\\MyOwnReport.html”);
Extent = new ExtentReports();
Extent.attachReporter(HtmlReporter);
Extent.setSystemInfo(“OS”, OS);
try {
Extent.setSystemInfo(“Host Name”, Inet4Address.getLocalHost().toString());
} catch (UnknownHostException e) {
e.printStackTrace();
}
Extent.setSystemInfo(“Web Browser”, BrowserName);
Extent.setSystemInfo(“Browser Version : “, Version);
HtmlReporter.config().setChartVisibilityOnOpen(true);
HtmlReporter.config().setDocumentTitle(“Logix Health Automation Test Report”);
HtmlReporter.config().setReportName(“Logix Express”);
HtmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
HtmlReporter.config().setTheme(Theme.STANDARD);
setExcelFile(ScrPath+DataFile);
driver.get(GetDatafromCell(“Global”, 2, “URL”));
driver.manage().window().setSize(new Dimension(1280, 1024));
Thread.sleep(3000);
SharedRepoInputFile = new FileInputStream(SharedRepofile);
sprops.load(SharedRepoInputFile);
AppRepoInputFile = new FileInputStream(ScrPath+AppRepofile);
aprops.load(SharedRepoInputFile);
login(GetDatafromCell(“Global”, 2, “UID”), GetDatafromCell(“Global”, 2, “PWD”));
Thread.sleep(5000);
}
@AfterSuite
public void afterSuite() {
File f = new File(System.getProperty(“user.dir”)+”\\CustomReport\\MyOwnReport.html”);
if (f.exists()) {
String oldtDir = System.getProperty(“user.dir”) + “\\CustomReport\\Old\\”;
File fold = new File(oldtDir);
//f= new File(“MyOwnReport.html”).renameTo(new SimpleDateFormat(“dd-MM-yyyy HH:mm:ss”).format(new Date()+”MyOwnReport.html”);
String rn = new SimpleDateFormat(“dd-MM-yyyy HH:mm:ss”)+”MyOwnReport.html”;
File nf = new File(rn);
f.renameTo(nf);
try {
FileUtils.moveFileToDirectory(f, fold, true);
} catch (IOException e) {
e.printStackTrace();
}
}
Extent.flush();
}
@BeforeMethod
public void beforeMethod(Method method) {
Test = Extent.createTest((this.getClass().getSimpleName()));
}
@Test
public void forTest() throws Exception {
driver.findElement(By.linkText(“Dashboard”)).click();
Thread.sleep(6000);
}
@Test
public void forTest2() throws Exception {
driver.findElement(By.linkText(“Work Queue”)).click();
driver.findElement(By.id(“toggleOutstanding”)).click();
Thread.sleep(3000);
}
@AfterMethod
public void getResult(ITestResult result) throws Exception{
if (result.getStatus() == ITestResult.FAILURE) {
// With Java Screen Capture
String imagepath = CaptureScreenShot(result.getName());
Test.log(Status.FAIL, MarkupHelper.createLabel(result.getName() + ” Test case FAILED due to below issues:”, ExtentColor.RED));
//Test.log(Status.FAIL, MarkupHelper.createLabel(result.getThrowable()+ ” Test case FAILED :”, ExtentColor.RED));
//Test.fail(result.getThrowable());
//Test.log(Status.FAIL, (Markup) Test.addScreenCaptureFromPath(imagepath));
//Test.log(Status.FAIL, Test.addScreenCaptureFromPath(imagepath));
Test.fail(“Snapshot below : ” + Test.addScreenCaptureFromPath(imagepath));
}
else if(result.getStatus() == ITestResult.SUCCESS){
Test.log(Status.PASS, MarkupHelper.createLabel(result.getName() + ” Test Case PASSED”, ExtentColor.GREEN));
}
else
{
Test.log(Status.SKIP, MarkupHelper.createLabel(result.getName() + ” Test Case SKIPPED”, ExtentColor.ORANGE));
Test.skip(result.getThrowable());
}
}
Hi Ramesh, try this OutputType.BASE64 instead of OutputType.FILE
You need to use new method called ‘MediaEntityBuilder’: https://github.com/anshooarora/extentreports-java/issues/726