QA AND TEST AUTOMATION · PART 7 · BDD AND FRAMEWORK DESIGN · BDD · 68 OF 112

Cucumber With Java: Steps, Hooks and Parallel Runs

Cucumber JVM with JUnit 5: the Maven setup with the Cucumber BOM, a runner class for the JUnit Platform, step definitions with Cucumber expressions, sharing state between steps with PicoContainer, hooks with tags and screenshots, data tables, tag expressions for smoke runs, parallel execution and reports, all built around the ShopRung coupon feature.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • BOM + JUnit Platform engine
  • suite runner
  • thin steps
  • PicoContainer context
  • tagged hooks
  • tables
  • parallel

Notes

Setup

Add the Cucumber BOM in dependency management, so all Cucumber modules share one version. Then cucumber java for the annotations, the cucumber JUnit platform engine so JUnit five can run features, cucumber picocontainer for sharing state, and the JUnit platform suite module for the runner. Feature files go under source, test, resources, features, so they are on the classpath.

pom.xml (test scope)
<dependencyManagement> io.cucumber
  :cucumber-bom:7.20.1 (import)
io.cucumber:cucumber-java
io.cucumber:cucumber-junit-
  platform-engine
io.cucumber:cucumber-picocontainer
org.junit.platform:
  junit-platform-suite

features: src/test/resources/
  features/coupons.feature

The runner

The runner is an empty class with annotations. Suite and include engines cucumber tell JUnit to use the Cucumber engine. Select classpath resource features says where the feature files are. The glue property names the package with your step definitions, and the plugin property adds output: pretty prints steps to the console, and html writes a report. Maven runs it with mvn test, like any JUnit test.

RunCucumberTest.java
@Suite
@IncludeEngines("cucumber")
@SelectClasspathResource("features")
@ConfigurationParameter(
  key = GLUE_PROPERTY_NAME,
  value = "dev.algorung.steps")
@ConfigurationParameter(
  key = PLUGIN_PROPERTY_NAME,
  value = "pretty, html:target/
    cucumber.html")
public class RunCucumberTest {}

Step definitions

Step definitions are methods annotated with given, when or then and a Cucumber expression. Int and string become method parameters, converted for you. Keep steps thin: each one calls a helper, here a ShopRung client, so the logic is reusable outside Cucumber. Assertions use JUnit's assert equals. When you run a feature with a step nobody wrote yet, Cucumber prints a ready made snippet to paste in.

CouponSteps.java
@Given("my cart has {int} {string}")
public void cartHas(int qty,
                    String name) {
  shop.addToCart(name, qty);
}
@When("I apply the coupon {string}")
public void apply(String code) {
  ctx.response = shop.coupon(code); }
@Then("the total is {string}")
public void total(String expected) {
  assertEquals(expected, ...); }

Sharing state

Steps in different classes need to share data: the login step stores a token, the coupon step needs it. Do not use static fields; they leak between scenarios and break parallel runs. With PicoContainer, declare a scenario context class and ask for it in each step class's constructor. Cucumber creates one context per scenario and gives the same instance to every step class in that scenario, then throws it away.

Dependency injection
public class ScenarioContext {
  String token;
  Response response;
}
public class CouponSteps {
  private final ScenarioContext ctx;
  public CouponSteps(
      ScenarioContext ctx) {
    this.ctx = ctx; }
}
// one new instance per scenario

Hooks

Hooks run around every scenario. A before hook resets ShopRung. Hooks can be limited by tag: before scenarios tagged at UI, start a browser; after them, if the scenario failed, attach a screenshot to the report with scenario dot attach, then quit the browser. API scenarios never pay the cost of starting a browser. Use hooks for setup and teardown only, never to hide test steps.

Hooks.java
@Before
public void resetShop() {
  shop.reset(); }
@Before("@ui")
public void startBrowser() { ... }
@After("@ui")
public void screenshot(Scenario s) {
  if (s.isFailed()) s.attach(
    screenshotBytes(), "image/png",
    s.getName());
  driver.quit(); }

Data tables

A step can carry a table. Here the cart contains two notebooks and one field guide. In the step definition, the table arrives as a list of maps, one map per row, keyed by the header. Cucumber can also convert rows straight into your own objects with a data table type. Tables keep scenarios readable when one step needs several values.

A table in a step
Given my cart contains:
  | product             | qty |
  | Clean Code Notebook | 2   |
  | Testing Field Guide | 1   |

@Given("my cart contains:")
public void cart(
    List<Map<String, String>> rows) {
  rows.forEach(r -> shop.addToCart(
    r.get("product"),
    Integer.parseInt(r.get("qty"))));

Tags

Tags label features and scenarios: smoke, UI, work in progress, a ticket number. Choose what runs with a tag expression on the command line, such as smoke and not work in progress, so the pipeline can run a quick smoke set on every commit and everything nightly. A dry run checks that every step has a definition without running anything, which is a fast check for pull requests.

Tags
@smoke
Scenario: SAVE10 applies at $50.00
@ui @wip
Scenario: ...

mvn test -Dcucumber.filter.tags=
  "@smoke and not @wip"

dry run (check every step has
  code): cucumber.execution
  .dry-run=true

Parallel and reports

Cucumber runs scenarios in parallel through the JUnit platform: enable it in the properties file and choose a fixed parallelism, such as four. It only works if scenarios share nothing: no static state, a driver per scenario, and their own data. Report plugins write HTML, JSON and JUnit XML; teams often add Allure, which comes later in this part.

junit-platform.properties
cucumber.execution.parallel
  .enabled = true
cucumber.execution.parallel
  .config.strategy = fixed
cucumber.execution.parallel
  .config.fixed.parallelism = 4

needs: no static state, own
  data per scenario
reports: html, json, junit;
  Allure plugin (Part 7, ep. 5)

Common mistakes

Cucumber Java mistakes. Static fields to share data between steps. Fat step definitions full of logic instead of calls to helpers. One step class per feature, with the same step written five times. Patterns so loose that two definitions match one step, which Cucumber reports as ambiguous. Hooks doing real test work nobody can see in the scenario. And parallel runs on shared data.

Avoid these
  • static fields to share data
  • fat steps full of logic
  • one step class per feature, duplicating steps
  • ambiguous patterns that match two steps
  • hooks doing test work
  • parallel on shared data

Say it like this

In the interview: feature files live under test resources, and a JUnit platform suite runner sets the glue package and report plugins. Step definitions are thin and call API clients and page objects. State between steps goes through a context object injected by PicoContainer, never static fields. Tagged hooks reset data, start browsers only for UI scenarios and attach screenshots on failure. Tags select smoke runs, and scenarios run in parallel with isolated data.

In the interview
  • "Features in resources, a JUnit Platform suite runner
  • with glue and plugins. Thin
  • steps call API clients and page
  • objects; state is shared via a PicoContainer context, never
  • statics. Tagged hooks reset
  • data and handle browsers and screenshots. Tags pick smoke
  • runs; scenarios run parallel."

Interview questions

Q1How do you run Cucumber with JUnit 5?

Add cucumber-junit-platform-engine and junit-platform-suite, then a runner class with @Suite, @IncludeEngines("cucumber"), @SelectClasspathResource("features") and configuration parameters for glue and plugins.

Q2What is the glue in Cucumber?

The package(s) where Cucumber looks for step definitions and hooks.

Q3How do you share state between step definition classes?

Dependency injection, for example PicoContainer: a context class injected through constructors, created fresh for each scenario. Not static fields.

Q4What are Cucumber hooks?

@Before and @After (and step-level hooks) that run around scenarios, optionally filtered by tags, used for setup, teardown and attaching evidence.

Q5How do you run only smoke scenarios?

Tag them @smoke and run with -Dcucumber.filter.tags="@smoke" (tag expressions support and, or, not).

Q6How do you handle a Gherkin data table in Java?

Accept a DataTable or List<Map<String, String>> parameter in the step definition, or register a data table type to convert rows to objects.

Q7How do you run Cucumber scenarios in parallel?

Enable cucumber.execution.parallel.enabled in junit-platform.properties with a parallelism setting, and keep scenarios independent (no static state, own data, own driver).

Q8What is a Cucumber dry run?

A run that matches every step to a definition without executing them, to find undefined or ambiguous steps quickly.