Saturday, 4 February 2017

Attaching Screenshot in Emailable HTML Report

Important part of automation is to generate test report after execution of test script.
As build release is dependent on the test report, it should be effective and clear enough to make the decision whether to hold release or move forward.

Selenium does not provide in built reporting functionality but we can use external libraries to generate the report.

There are number of reporting libraries available like Junit, TestNG and extent reports.

I would preferably use Extent Report as it provides simple and interactive UI.
2017-02-03 16_36_08-Test.png



For failed test cases it is important to know the cause of failure. In the test script we can use Capture Screen shot method to get screenshot of failed Test Cases and attached them in HTML report.

File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File screenshotLocation = new File(“filename.png”);
FileUtils.copyFile(screenshot, screenshotLocation);
extent.addScreenshot(“filename.png”);

The issue with this is, if we sent HTML report as attachment in email then we won’t be able to view attached screenshot. In HTML report, path of screenshot is of local system which won’t be accessed from any other location.

In order to overcome this issue we can convert image file to base64 format and then attach them in HTML report.

Below is the sample code to convert screenshot in Base64 format and attached them in HTML report

public static void captureScreenshot(String TCName, String TSID) throws IOException, InterruptedException
  {
   File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File screenshotLocation = new File(Constants.dir+"\\screenshots+TCName+"_"+TSID+".png");
FileUtils.copyFile(screenshot, screenshotLocation);
Thread.sleep(2000);
InputStream is = new FileInputStream(screenshotLocation);
byte[] imageBytes = IOUtils.toByteArray(is);
Thread.sleep(2000);
String base64 = Base64.getEncoder().encodeToString(imageBytes);
Extent.log(LogStatus.INFO, "Snapshot below: " + extent.addBase64ScreenShot("data:image/png;base64,"+base64));    
  }

2 comments:

  1. Hi Gaurav,

    I am not able to configure Constants.dir can you help me for this
    File screenshotLocation = new File(Constants.dir+"\\screenshots+TCName+"_"+TSID+".png");
    thanks
    Mohit

    ReplyDelete
  2. There is no toBytesArray fun inside IOUtils class. Please guide

    ReplyDelete