Hooks are blocks of code that can run at various points in the Cucumber execution cycle. They are typically used for setup and teardown of the environment before and after all/each scenario or step.
See the reference documentation.
Static hooks run once before/after all scenarios.
Note: static hooks can only be defined inside object
s (not classes).
BeforeAll
hooks run once before all scenarios.
BeforeAll {
// Do something before all scenarios
// Must return Unit
}
AfterAll
hooks run once after all scenarios.
AfterAll {
// Do something after each scenario
// Must return Unit
}
Scenario hooks run for every scenario.
Before
hooks run before the first step of each scenario.
Before { scenario : Scenario =>
// Do something before each scenario
// Must return Unit
}
// Or:
Before {
// Do something before each scenario
// Must return Unit
}
After
hooks run after the last step of each scenario.
After { scenario : Scenario =>
// Do something after each scenario
// Must return Unit
}
// Or:
After {
// Do something after each scenario
// Must return Unit
}
Step hooks invoked before and after a step.
BeforeStep { scenario : Scenario =>
// Do something before step
// Must return Unit
}
// Or:
BeforeStep {
// Do something before step
// Must return Unit
}
AfterStep { scenario : Scenario =>
// Do something after step
// Must return Unit
}
// Or:
AfterStep {
// Do something after step
// Must return Unit
}
Hooks can be conditionally selected for execution based on the tags of the scenario.
Before("@browser and not @headless") {
// Do something before each scenario with tag @browser but not @headless
// Must return Unit
}
Note: this cannot be applied to static hooks (BeforeAll
/AfterAll
).
You can define an order between multiple hooks.
Before(10) {
// Do something before each scenario
// Must return Unit
}
Before(20) {
// Do something before each scenario
// Must return Unit
}
The default order is 1000.
You mix up conditional and order hooks with following syntax:
Before("@browser and not @headless", 10) {
// Do something before each scenario
// Must return Unit
}
Note: this cannot be applied to static hooks (BeforeAll
/AfterAll
).