Cucumber | @Before hook Vs Background | Usage

Priyank Shah
2 min readMar 15, 2019

--

Assumption here — we have good understanding of following tool / terminologies.

What are Hooks and “@Before” hook?

Cucumber supports hooks, which are blocks of code that run before or after each scenario. Cucumber Hooks allows us to better manage the code workflow and helps us to reduce the code redundancy.

  • We can say that it is an unseen step, which allows us to perform our scenarios or tests.
  • They are typically used for setup and tear down of the environment before and after each scenario.
  • @Before and @After tagging a method with either of these will cause the method to run before or after each scenario runs. They will run in the same order of which they are registered.
  • Common functionality like starting or stop browsers are nice to place in these hooks.

What is Background?

Sample feature file
  • Use Background only to setup a pre-condition that the user needs to know
  • Occasionally you’ll find yourself repeating the same Given steps in all of the scenarios in a feature. You can literally move such repeating Given steps to the background, by grouping them under a Background section.
  • A Background is run before each scenario, but after any Before hooks. In your feature file, put the Background before the first Scenario

Execution order of @before vs Background

Execution Order of @Before and Background
  • The main thing to understand here is the order of the operations:
  • Before Hook 1 -> Before Hook 2 -> … -> Background -> Scenario
  • Before hooks will be run before the first step of each scenario. They will run in the same order of which they are registered. After hooks will be run after the last step of each scenario, even when there are failing, undefined, pending or skipped steps.

Summary

--

--

Priyank Shah
Priyank Shah

Written by Priyank Shah

Agile Product Leader | Delivery Manager | Design Thinker (PRINCE2, CSPO™, CSM™, SFC™, ISTQB)

Responses (3)