Automatically take a screenshot on failure of a Cucumber scenario

If you are using Cucumber to automate testing your web application, it can be useful to include a screenshot in Cucumber’s report whenever a scenario fails.

Cucumber itself doesn’t provide functionality for taking screenshots, but it does make it possible to embed them in the report. If you are using Cucumber together with a Selenium WebDriver, which can capture screens, it’s easy as pie. All you have to do is paste the following lines of Java code into your Cucumber steps definition:

9 Replies to “Automatically take a screenshot on failure of a Cucumber scenario”

  1. Can you please provide information on what to pass to Scenario parameter in screenshot method “public void tearDown(Scenario scenario)”

  2. Thanks for your information.
    Appreciate if you can through some light on this….

    ********************************************************************************************************************************************************************
    @Test(groups = “cucumber”, description = “Check WR report”, dataProvider = “features”)
    public void feature(CucumberFeatureWrapper cucumberFeature) {

    testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
    Scenario scenario=(Scenario)testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
    if (scenario.isFailed()) {
    String screenshotName = scenario.getName().replaceAll(” “, “_”);
    try {
    TakesScreenshot ts = (TakesScreenshot) driver;
    File sourcePath = ts.getScreenshotAs(OutputType.FILE);
    File destinationPath = new File(
    System.getProperty(“user.dir”) + “\\target\\cucumber-reports\\screenshots\\” + screenshotName + “.png”);
    FileUtils.copyFile(sourcePath, destinationPath);
    Reporter.addScreenCaptureFromPath(destinationPath.toString());
    } catch (WebDriverException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }
    }
    **************************************************************************************************************************************************************

    Please explain my fault areas and suggest .

  3. if you want at some specific location then execute code like this..

    if (scenario.isFailed()) {
    File scrFile = ((TakesScreenshot)dictionaryPage.getDriver()).getScreenshotAs(OutputType.FILE);

    try {
    FileUtils.copyFile(scrFile, new File(“C:/Users/Public/Downloads/TestScreenshot/Error.jpg”));
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

  4. it embeds screenshot in cucumber report found in the target directory.

Comments are closed.