Execution Logic for Global and Tagged Hooks
In Cucumber (specifically Cucumber-JVM), the order parameter applies collectively across all matching hooks. There is no inherent priority given to tagged hooks over global hooks; rather, the tagging mechanism acts as a filter to determine which hooks are added to the execution pool for a specific scenario. Once the pool of applicable hooks is identified, the order value dictates the sequence.
Execution Rules
- @Before Hooks: Executed in ascending order (lowest value first).
- @After Hooks: Executed in descending order (highest value first).
If a scenario matches both a global hook and a tagged hook, they are sequenced relative to each other based strictly on their assigned order values. If two tagged hooks match, they follow the same ascending/descending rules as global hooks.
Practical Implementation and Verification
To verify this behavior in your environment, implement the following hook configuration and observe the console output:
@Before(order = 1)
public void globalBefore() {
System.out.println("Global Before (1)");
}
@Before(value = "@tagged", order = 0)
public void taggedBeforeLow() {
System.out.println("Tagged Before (0)");
}
@Before(value = "@tagged", order = 2)
public void taggedBeforeHigh() {
System.out.println("Tagged Before (2)");
}
@After(order = 1)
public void globalAfter() {
System.out.println("Global After (1)");
}
@After(value = "@tagged", order = 0)
public void taggedAfterLow() {
System.out.println("Tagged After (0)");
}
@After(value = "@tagged", order = 2)
public void taggedAfterHigh() {
System.out.println("Tagged After (2)");
}
Expected Output for a @tagged Scenario
| Phase |
Expected Sequence |
Logic |
| Setup |
Tagged(0) → Global(1) → Tagged(2) |
Ascending order |
| Teardown |
Tagged(2) → Global(1) → Tagged(0) |
Descending order |
Assumptions and Constraints
This behavior is based on the Cucumber-JVM implementation. While most Cucumber implementations follow similar logic, some language-specific versions (such as Ruby or JS) may handle default ordering differently.
Warning: Hooks without an explicit order parameter typically default to 0. Mixing hooks with explicit orders and those without can lead to unpredictable sequencing if you rely on the default value for critical setup steps.
To provide a more tailored recommendation, please specify which Cucumber language implementation (e.g., Java, JS, Ruby) and version you are currently using.