Add Screenshot in Cucumber Extent Report

Profile picture for user devraj

There could be several ways to implement screenshot utility with Cucumber Adapter. Two of them are discussed below, you can use either one depending on your requirement. 

Table of Content

  1. Method 1 - Screenshot in Byte Format
  2. Method 2 - Screenshot as Base64
  3. Video Tutorial

Method 1: Attach Screenshot in Byte Format

The advantage of using this method is that your report file size will be less, but the problem is if you will send reports as an email attachment. The screenshot will not display on the other's machine.

Step 1: Add method to capture screenshot

public byte[] getByteScreenshot() throws IOException 
{
    File src = ((TakesScreenshot) base.getDriver()).getScreenshotAs(OutputType.FILE);
    byte[] fileContent = FileUtils.readFileToByteArray(src);
    return fileContent;
}

Here,

  • TakeScreenshot is an interface that Indicates a driver that can capture a screenshot and store it in different ways. 
  • FileUtil is general file manipulation util. readFileToByteArray will read the content of image file in ByteArray. 

or You can directly convert to byte and return

public byte[] getByteScreenshot()
{
    return ((TakesScreenshot) base.getDriver()).getScreenshotAs(OutputType.BYTES);
}

Step 2: Add Screenshot configuration in extent.properties located at src/test/resources/

screenshot.dir=test-output/screenshots/
screenshot.rel.path=../screenshots/

Step 3: In after hook call following line

@After
public void af(Scenario scenario) throws IOException, InterruptedException
{
    if(scenario.isFailed())
    {			
        scenario.attach(getByteScreenshot(), "image/png", scenario.getName());
    }
    base.getDriver().quit();
}

Method 2: Attach Screenshot in Base64 Format 

The advantage of using this method is that screenshots will display on other's machines if you send the report as an email attachment. The disadvantage is that the report size file will be large as more number of screenshot attach on failure. Also, with the same approach, you can get out of memory errors on Jenkins or other machines if you run thousands of scripts in a single job.

Step 1: Add method to generate Base 64

public String getBase64Screenshot()
{
    return ((TakesScreenshot) base.getDriver()).getScreenshotAs(OutputType.BASE64);
}

Step 2: Add Screenshot configuration in extent.properties located at src/test/resources/

screenshot.dir=test-output/screenshots/
screenshot.rel.path=../screenshots/

Step 3: In @After Hook call following lines

@After
public void af(Scenario scenario) throws IOException, InterruptedException
{
    if(scenario.isFailed())
    {		       
        ExtentCucumberAdapter.getCurrentStep().log(Status.FAIL, MediaEntityBuilder.createScreenCaptureFromBase64String(getBase64Screenshot()).build());
    }
	 base.getDriver().quit();
}