0

could you tell me how to generate pretty html reports with screenshot ? After I run the test the "cucumber-reports.html" does not exist. Only "image.png" file is generated.

  package cucumber.Options;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(features="src/test/java/features",
        plugin = {"pretty", "html:target/reports/cucumber-reports.html"},
        glue= {"stepDefs"},
        stepNotifications = true,
        monochrome = true
        )
public class TestRunner {
}

Method that does screenshot

@After
    public void afterTest(Scenario scenario) throws IOException {
        if (!scenario.isFailed()) {
           // String destination = System.getProperty("user.dir") + "//src" + "//Screenshots" + scenario + ".png";

            final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            scenario.attach(screenshot, "image/png", scenario.getName());
            String directory = System.getProperty("user.dir") + "//target" + "//reports";
            File sourceFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(sourceFile, new File(directory, "image.png"));
        }

        if (driver != null) {
            driver.quit();
        }
    }

pom file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Cucumber</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>


    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.4.0</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.testng/testng -->

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>7.8.1</version>
        </dependency>



        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-junit -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>7.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.assertj/assertj-core -->
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>3.23.1</version>
            <scope>test</scope>
        </dependency>


        <!-- https://mvnrepository.com/artifact/io.github.bonigarcia/webdrivermanager -->
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.11</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>31.1-jre</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.8.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
            <scope>compile</scope>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>2.0.7</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>2.0.7</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->

        <!-- https://mvnrepository.com/artifact/com.opencsv/opencsv -->
        <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>5.7.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/picocontainer/picocontainer -->
        <!-- https://mvnrepository.com/artifact/picocontainer/picocontainer -->
        <!-- https://mvnrepository.com/artifact/picocontainer/picocontainer -->
        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-picocontainer -->
        <!-- https://mvnrepository.com/artifact/picocontainer/picocontainer -->


        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-picocontainer -->
        <!-- https://mvnrepository.com/artifact/picocontainer/picocontainer -->
        <dependency>
            <groupId>picocontainer</groupId>
            <artifactId>picocontainer</artifactId>
            <version>1.2</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/de.monochromata.cucumber/reporting-plugin -->
        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-html -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-html</artifactId>
            <version>0.2.7</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin -->


        <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin -->
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java8 -->
        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-core -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>7.11.2</version>
        </dependency>



    </dependencies>

</project>

2 Answers 2

0

To generate pretty HTML reports with screenshots in Cucumber, you can use the Cucumber HTML Reporter plugin. Here are the steps to implement it:

1 Add the dependency for the Cucumber HTML Reporter plugin to your pom.xml file:

<dependency>
    <groupId>net.masterthought</groupId>
    <artifactId>cucumber-reporting</artifactId>
    <version>5.6.0</version>
</dependency>

2 Modify your CucumberOptions annotation to include the plugin and set the plugin attribute to use the

com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter: prefix.
@CucumberOptions(
    plugin = {
        "pretty",
        "com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:"
    },
    ...
)

3 Create a new class called ExtentReportListener that extends AbstractTestNGCucumberTests and implements the IReporter interface. This class will be responsible for generating the HTML report.

public class ExtentReportListener extends AbstractTestNGCucumberTests implements IReporter {

    private ExtentReports extent;
    private static final String OUTPUT_FOLDER = "target/";
    private static final String FILE_NAME = "cucumber-extent.html";

    @Override
    public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
        init();
        for (ISuite suite : suites) {
            Map<String, ISuiteResult> result = suite.getResults();
            for (ISuiteResult r : result.values()) {
                ITestContext context = r.getTestContext();
                buildTestNodes(context.getPassedTests(), Status.PASS);
                buildTestNodes(context.getFailedTests(), Status.FAIL);
                buildTestNodes(context.getSkippedTests(), Status.SKIP);
            }
        }
        extent.flush();
    }

    private void init() {
        ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(OUTPUT_FOLDER + FILE_NAME);
        htmlReporter.config().setEncoding("utf-8");
        htmlReporter.config().setDocumentTitle("Automation Test Results");
        htmlReporter.config().setReportName("Automation Test Results");
        htmlReporter.config().setTheme(Theme.STANDARD);

        extent = new ExtentReports();
        extent.attachReporter(htmlReporter);
        extent.setReportUsesManualConfiguration(true);
    }

    private void buildTestNodes(IResultMap tests, Status status) {
        ExtentTest test;
        if (tests.size() > 0) {
            for (ITestResult result : tests.getAllResults()) {
                test = extent.createTest(result.getMethod().getMethodName());
                for (String group : result.getMethod().getGroups())
                    test.assignCategory(group);
                if (result.getThrowable() != null) {
                    test.log(status, result.getThrowable());
                } else {
                    test.log(status, "Test " + status.toString().toLowerCase() + "ed");
                }
                if (result.getStatus() == ITestResult.FAILURE) {
                    try {
                        test.fail("Screenshot",
                                MediaEntityBuilder.createScreenCaptureFromPath(takeScreenshot()).build());
                    } catch (IOException e) {
                        test.fail("Screenshot not available");
                    }
                }
                extent.flush();
            }
        }
    }

    private String takeScreenshot() {
        String fileName = "screenshot.png";
        String directory = OUTPUT_FOLDER + "screenshots/";
        new File(directory).mkdirs();
        File sourceFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(sourceFile, new File(directory + fileName));
        } catch (IOException e) {
            fileName = "screenshot-not-available.png";
        }
        return directory + fileName;
    }
}

4 In the ExtentReportListener class, you will also need to create a method to take a screenshot of the web page when a test fails. The method should return the path to the screenshot file.

5 Modify your step definitions to use the ExtentCucumberAdapter. To do this, add the following line to the top of your step definitions file: @ExtendWith({ExtentCucumberAdapter.class})

6 Finally, run your tests with TestNG, and the HTML report with screenshots will be generated in the target/cucumber-reports/cucumber-extent.html file.


Another way to generate pretty HTML reports with screenshots in Cucumber, you can use the Cucumber Extent Reporter plugin. This plugin provides a comprehensive and customizable HTML report with detailed information on the test results along with the screenshots.

Here are the steps to add the Cucumber Extent Reporter plugin to your project:

1 Add the following dependency to your pom.xml file:

<dependency>
    <groupId>com.aventstack</groupId>
    <artifactId>extentreports-cucumber6-adapter</artifactId>
    <version>3.1.2</version>
</dependency>

2 Update the @CucumberOptions annotation in your TestRunner class as follows:

@CucumberOptions(features="src/test/java/features",
        plugin = {"pretty", "com.aventstack.extentreports.cucumber.adapter.ExtentCucumberAdapter:"},
        glue= {"stepDefs"},
        stepNotifications = true,
        monochrome = true
        )
public class TestRunner {
}

3 Modify your @After method to include the following code:

@After
public void afterScenario(Scenario scenario) {
    if (scenario.isFailed()) {
        try {
            byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            scenario.attach(screenshot, "image/png", scenario.getName());
            extentTest.fail("Test Failed");
            extentTest.addScreenCaptureFromBase64String(new String(screenshot), scenario.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        extentTest.pass("Test Passed");
    }
    driver.quit();
}

4 Create an extent-config.xml file in your project and add the following code:

<?xml version="1.0" encoding="UTF-8"?>
<extent>
    <configuration>
        <!-- report theme -->
        <theme>standard</theme>
        <!-- document encoding -->
        <encoding>UTF-8</encoding>
        <!-- protocol for script and stylesheets -->
        <protocol>https</protocol>
        <!-- title of the document -->
        <documentTitle>Cucumber Extent Report</documentTitle>
        <!-- report name - displayed at top-nav -->
        <reportName>Cucumber Extent Report</reportName>
        <!-- location of charts in the report -->
        <chartLocation>./</chartLocation>
        <!-- time zone for timestamps -->
        <timeZone>UTC</timeZone>
    </configuration>
</extent>

5 Finally, run your test suite and the HTML report will be generated in the output folder. Note: You may need to modify the code to suit your project's requirements.


Here's how to add the extentTest:

1 Declare a global ExtentReports and ExtentTest object in your

TestRunner class:
public class TestRunner {
    private static ExtentReports extentReports;
    private static ExtentTest extentTest;
    // ...
}

2 Initialize the extentReports object in the @BeforeClass method:

@BeforeClass
public static void beforeClass() {
    String reportPath = "./output/extent-report.html";
    ExtentSparkReporter sparkReporter = new ExtentSparkReporter(reportPath);
    sparkReporter.config().setReportName("Cucumber Extent Report");
    extentReports = new ExtentReports();
    extentReports.attachReporter(sparkReporter);
}

3 Create an instance of ExtentTest in the @Before method: @Before public void beforeScenario(Scenario scenario) { extentTest = extentReports.createTest(scenario.getName()); // ... }

ExtentTest is a class provided by the ExtentReports library to create test logs in the report. In the provided code, extentTest is an instance of the ExtentTest class which is created in the @Before method of the TestRunner class. This instance is then used to log the status of the test and attach screenshots in the @After method.

The ExtentTest class has several methods to log information about the test such as pass(), fail(), warning(), skip(), etc. You can call these methods on the extentTest instance to log the test status. For example, in the provided code, extentTest.pass("Test Passed") is used to log the test passed status and extentTest.fail("Test Failed") is used to log the test failed status.

Additionally, you can also log other information about the test such as the test description, author, category, etc. using the ExtentTest class methods. For example, extentTest.info("Test Description") can be used to log the test description. You can refer to the ExtentReports documentation for more information on how to use the ExtentTest class to log information in the report.

I hope this helps you generate pretty HTML reports with screenshots in your Cucumber project.

2
  • second solution seems faster but where is class ExtentTest ? extentTest.fail("Test Failed"); extentTest.addScreenCaptureFromBase64String(new String(screenshot), scenario.getName()); May 1, 2023 at 10:05
  • can you show the code of ExtentTest class ? May 2, 2023 at 6:23
0

First of all we should take screenshot on the failure. For passed test cases its not required.

And use below code. Why are you coping the screenshot?

@After()
    public void tearDown(Scenario scenario){
        if (scenario.isFailed()) {
            byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            scenario.attach(screenshot, "image/png", "Screenshot");
        }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.