How to Add Screenshot in Cucumber Extent Report for Every Step

Profile picture for user devraj

Adding screenshot for each step is pretty simple you just need to use AfterStep hook. Below code is tested with Cucumber version 6.8.1 and tech.grassshopper extent cucumber6 adapter version 1.2.0.

@AfterStep
public void as(Scenario scenario) throws IOException, InterruptedException
{
    scenario.attach(GenericFunctions.getByteScreenshot(), "image/png", "screenshot name");		
}

Here we have used attach() method you can also use addTestStepScreenCaptureFromPath of ExtentCucumberAdapter for that view this article.

In above code scenario is an object of class Scenario, attach() is a method of Scenario class which accepts 3 parameters data we want to attach, here we are sending image in byte format, then mediaType is image png, after that you can give any name.

Inside GenericFunctions class we have created one method getByteScreenshot():

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

Here after capturing screenshot as a file, we are reading the contents of a file into a byte array and then returning it inside attach method.

Also, make sure these 4 parameters are configured properly in your extent.properties file:

extent.reporter.html.start=true
extent.reporter.html.out=test-output/HtmlReport/ExtentHtml.html
screenshot.dir=test-output/screenshots/
screenshot.rel.path=../screenshots/