Search code examples
cucumbertestngcucumber-java

How to attach screenshot to steps using AbstractTestNGCucumberTests?


I want to attach screenshot to steps that is generated cucumber html report. My project use AbstractTestNGCucumberTests.

This is my takeScreenshot method:

public static void takeScreenshot(io.cucumber.core.api.Scenario scenario,
                                  WebDriver driver, File screenShotFile) {
    final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
    scenario.embed(screenshot, "image/png");
    try {
        OutputStream os = new FileOutputStream(screenShotFile);

        os.write(screenshot);
        Log.debug("Successfully save screenshot");

        os.close();
    } catch (Exception ex) {
        Log.error("Exception : " + ex);
    }
}

I try to get Scenario by declaring anotation io.cucumber.java.Before enter image description here

But Scenario is null

Please help me how to get io.cucumber.core.api.Scenario or another way to attach screenshot in steps for reporting


Solution

  • I fixed my problem. Cucumber hook @Before is just run in location that is defined in @CucumberOptions(glue=my-path). My Class TestSuiteMaster is in another path, so Scenario is null.

    I created a class CucumberHook in directory stepDefinition and take screen shot method in hook @After, everything work great.

    This is my CucumberHook class:

    public class CucumberHook extends WebTestSuiteMaster {
    
        @After
        public void take_screenshot_after_finished_scenario(Scenario scenario) {
            String imageFileName = "Screen shot-" + scenario.getName() + "-"
                    + new SimpleDateFormat("MM-dd-yyyy_HH-mm").format(new Date()) + ".png";
            File imageFile = new File(System.getProperty("user.dir") + "//screenshots//" + imageFileName);
    
            SeleniumWebHelper.takeScreenshot(scenario, driver, imageFile);
        }
    }