Embedding screenshots in Cucumber JVM

I was trying to improve our automated test suite and I thought that it could be useful to capture a screenshot of the browser whenever a test fails.
The current Cucumber JVM implementation highly simplifies this task, but the task is not achieved the way I thought, so this is the reason for this post.

Normally you would use a JUnit TestRule to augment all your test cases with a feature to take screenshots, but for Cucumber JVM it’s much easier thankfully to the Execution Hooks:

public class ScreenshotHook {
  private WebDriver driver;

  public void embedScreenshot(Scenario scenario) {
    if (scenario.isFailed()) {
      try {
        byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        scenario.embed(screenshot, "image/png");
      } catch (WebDriverException wde) {
      } catch (ClassCastException cce) {

As you can see I’m injecting the WebDriver instance (I’m using the Cucumber JVM Spring integration) and defining an embedScreenshot method which is annotated with cucumber.annotation.After: this is the important bit because methods annotated as such will be executed after each cucumber scenario.

For sake of completeness I want to tell you there is another hook cucumber.annotation.Before that can be used for things like logging into your application eliminating those repetitive log in steps.

Please note that in pre 1.1.0 versions of Cucumber JVM Scenario was ScenarioResult.

4 thoughts on “Embedding screenshots in Cucumber JVM

  1. The Driver is injected by Spring, the Scenario is passed in by the framework when calling the method annotated as After: isn’t that already explained in the post?


  2. Hello, I tried the same code but I am getting “The method embed(byte[], String) is undefined for the type Scenario” error
    public takeScreenshot(Scenario scenario){
    final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
    scenario.embed(screenshot, “image/png”);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s