Search code examples
javaunit-testingseleniumjunitcucumber-jvm

java - Cucumber on JUnit Test Failure Hook


We use Cucumber-JVM to script our acceptance tests and JUnit to execute them (via the JUnit Cucumber runner). As these tests involve Selenium WebDriver, I want to be able to take a screenshot should my test fail (which I have the code for).

If I simply add a WebDriver onException hook, the screenshot won't be taken when an assertion fails. I want to be able to add a JUnit execution listener to the Cucumber runner, but the API doesn't seem to support this (no addListener method on Cucumber.class).

Can anyone help? Thanks team.


Solution

  • I generally take screenshots in the @After hook which gets called after every cucumber scenario. @After hook method takes a special Scenario object so that you can embed your screenshots in your reports. Here is an example on how to take screenshots in the event your scenario fails,

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