Search code examples
javacucumberscreenshot

Screenshot on failure with Java + Cucumber


I've found what looks to be a widely-used method to capture screenshots on failure when using Java + Cucumber, which is nice and easy:

@After
public void embedScreenshot(Scenario scenario) throws Exception {
    if (scenario.isFailed()) {
        try {
            byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
            String testName = scenario.getName();
            scenario.embed(screenshot, "image/png");
            scenario.write(testName);
        } catch (WebDriverException wde) {
            System.err.println(wde.getMessage());
        } catch (ClassCastException cce) {
            cce.printStackTrace();}
        }
    }
}  

How would I write the image file to a folder on the desktop, for example, instead of the project directory by default, and give it a custom name such as the name of my Cucumber test scenario?


Solution

  • You can get the scenario name from the Scenario scenario like this:

    scenario.getName()
    

    Then you can just create two File objects, one for the screenshot and one of the the destination and use the org.apache.commons.io.FileUtils to copy the screenshot file to destination folder:

    FileUtils.copyFile(file, destFile);