Cucumber Annotations & Hooks in Java: A Practical Guide
In this article
Cucumber annotations and hooks in Java let you control when test code runs and how it shares data with your step definitions. You use annotations like @Given, @When, and @Then to map Gherkin steps to Java methods, and hooks like @Before and @After to run setup and teardown logic around each scenario or step. This guide explains how they work, how to use them correctly, and the common pitfalls that trip up beginners.
What Are Cucumber Annotations?
Cucumber is a testing framework that supports Behavior-Driven Development (BDD). You write test scenarios in plain text using Gherkin syntax (Given/When/Then), and then you write Java code that makes those steps do real things. The glue between the Gherkin text and the Java code is a set of annotations from the io.cucumber.java package.
- @Given – sets up the initial state (e.g., “Given a user is logged in”).
- @When – performs an action (e.g., “When the user clicks the submit button”).
- @Then – verifies the outcome (e.g., “Then the user sees a confirmation message”).
- @And and @But – refine the previous step; they are aliases for the last used annotation.
Each annotation takes a string pattern that can include placeholders like {int} or {string} to capture values from the Gherkin step. For example:
@Given("the user has {int} items in cart")
public void user_has_items_in_cart(int count) {
// setup code
}
The method parameters are automatically filled by Cucumber based on the pattern. You can also use regular expressions instead of the built-in parameter types, but the simpler {word}, {int}, and {string} are usually enough.
How Hooks Work in Cucumber
Hooks are methods that run at specific points during the test lifecycle. They are not tied to a Gherkin step; they run automatically based on their annotation. The most common are:
- @Before – runs before each scenario (or step if you use the
orderattribute). - @After – runs after each scenario, even if the scenario fails.
- @BeforeStep and @AfterStep – run before and after each step within a scenario.
You can tag hooks to run only for specific scenarios by using a tag expression in the annotation, like @Before("@smoke"). This is useful when you need different setup for different test groups.
A typical use is to initialize a WebDriver instance in a @Before hook and quit it in @After. To share that driver with step definitions, you can use dependency injection (like PicoContainer or Spring) or a static field. The example below shows a simple static approach:
public class Hooks {
public static WebDriver driver;
@Before
public void setUp() {
driver = new ChromeDriver();
}
@After
public void tearDown() {
if (driver != null) driver.quit();
}
}
Hooks run in the same thread as the scenario, so you can safely store data in Scenario object passed to the hook method to pass information to step definitions.
How to Choose Between Hooks and Background
Gherkin also has a Background keyword that runs before each scenario in a feature file. So when should you use a hook versus a background?
- Use Background when the setup is part of the business scenario and should be visible in the feature file (e.g., “Given a user is logged in”).
- Use @Before for technical setup that the business user doesn’t need to see (e.g., launching a browser, cleaning a database).
If you need to run the same technical setup for every scenario across all features, a global hook is better than repeating a background in every file. If the setup is specific to one feature, a background is more readable.
Common Mistakes and How to Avoid Them
Several mistakes trip up new Cucumber users:
- Mismatched step patterns – If your Gherkin step says “I have 5 apples” and your annotation says
@Given("I have {int} oranges"), Cucumber will not find a match. Always keep the text consistent. - Multiple step definitions for the same pattern – Cucumber will throw an ambiguity error if two methods match the same step. Use unique patterns or combine them with optional groups.
- Forgetting to add the Cucumber Java dependency – Without
io.cucumber:cucumber-javain your build, the annotations won’t be available. Maven users needcucumber-javaandcucumber-junit(or TestNG) to run. - Using hooks for business steps – Hooks run automatically, so they should not contain assertions or business logic that the scenario should explicitly state. Keep them for technical setup.
- Ignoring the
Scenarioobject – TheScenarioparameter in@Beforeand@Afterlets you write to the report (e.g.,scenario.log("...")) and mark the scenario as failed. Use it for debugging.
Comparison: JUnit vs. Cucumber Hooks
JUnit has its own lifecycle annotations like @BeforeEach and @AfterEach. If you are using JUnit to run Cucumber, you might wonder which one to use.
- JUnit hooks run around the entire test runner class, not around each scenario. If you have multiple scenarios in a feature,
@BeforeEachwill run before each scenario only if you are using a JUnit@RunWith(Cucumber.class)runner, but the behavior can be confusing. - Cucumber hooks are designed specifically for the BDD lifecycle and give you fine-grained control (before/after scenario, before/after step).
In practice, most teams use Cucumber hooks for browser setup and JUnit for test-level configuration like parallel execution settings. Mixing them is fine, but be aware that JUnit’s @BeforeAll runs once for the whole suite, not per scenario.
Cost and Performance Considerations
Hooks add overhead to every scenario. A @Before hook that launches a browser can take several seconds, which multiplies across hundreds of scenarios. To keep test suites fast:
- Use
@Beforeonly when necessary; avoid heavy operations in hooks that run for every scenario. - Consider using
@BeforeAll(JUnit) or a static initializer for one-time setup like database connections. - Use tags to run expensive hooks only for the scenarios that need them.
There is no monetary cost to using Cucumber; it’s open-source. The “cost” is in test execution time and maintenance. Poorly written hooks that duplicate setup logic can make the suite slower and harder to maintain.
Alternatives to Cucumber for BDD in Java
Cucumber is the most popular BDD framework for Java, but it’s not the only one. Alternatives include:
- JBehave – Similar to Cucumber but uses a different syntax and is less actively maintained.
- Serenity BDD – Built on top of Cucumber, adds reporting and living documentation features.
- TestNG with DataProvider – Not BDD, but you can write data-driven tests without Gherkin.
If you don’t need the business-readable Gherkin layer, a plain JUnit/TestNG test may be simpler. But if your team uses BDD to collaborate with non-technical stakeholders, Cucumber is the standard choice because it integrates well with CI/CD tools and has a large ecosystem.
Frequently Asked Questions
What is the difference between @Before and @BeforeAll in Cucumber?
@Before in Cucumber runs before each scenario, while @BeforeAll (from JUnit) runs once before any scenario in the test suite. Use @Before for per-scenario setup like clearing cookies, and @BeforeAll for one-time setup like opening a database connection.
Can I use multiple @Before hooks in the same class?
Yes, you can have as many @Before hooks as you need. They run in a predictable order if you specify the order attribute (lower numbers first). If you don’t specify order, the execution order is undefined, so it’s best to set it explicitly.
How do I pass data from a hook to a step definition?
You can store data in a static field, but a cleaner way is to use dependency injection. Cucumber supports PicoContainer, Spring, and other DI frameworks. For example, you can create a class that holds the WebDriver instance and inject it into both the hook and step definitions.
Why is my @After hook not running when a scenario fails?
@After hooks always run, even if the scenario fails. If your hook isn’t running, check that the class is in the same package as your step definitions and that Cucumber scans it. Also, make sure you haven’t accidentally placed the hook in a class that is not picked up by the glue path.
Can I use regular expressions in Cucumber annotations?
Yes, you can use full regular expressions. For example, @Given("^I have (\\d+) apples$") captures one or more digits. However, the built-in parameter types like {int} and {word} are easier to read and less error-prone.
Is it better to use hooks or a Background for login setup?
If login is a business requirement that the reader of the feature should see, use a Background. If login is a technical necessity (e.g., creating a session via API), a hook is fine. The key is whether the step adds business meaning to the scenario.