How To Use Annotations In Cucumber Framework

Related Product On This Page Setting up for Cucumber TestingMay 09, 2026 · 12 min read · Testing Guide

Related Product

How To Use Annotations In Cucumber Framework

The existence of testing has a lot of frameworks that have quicken the growth round, one of which is the. It can be easily understood even by someone who does not have the technical expertise.

Cucumber is a testing framework that supports Behavior Driven Development (BDD). This technique can be well understood by all the contributors to the undertaking, such as QA, Business Analysts, etc. Cucumber ’ s germ was originally written in the Ruby lyric and was later extended to Java.

Cucumber users annotating to define or describe an action. It is a predefined text that help the compiler understand and execute the bidding accordingly. This usher explains how to use annotations in Cucumber.

Setting up for Cucumber Testing

Let ’ s first set up the project using the Cucumber framework.

  • Step 1: Install IDE and Set up Java

You can establish any IDE, however, for the sake of this tutorial, let us useEclipse IDE. Also, establish the latest adaptation of Java on your system. To check that Java is installed on your scheme, run a quick command in the terminal to check the Java version.

Java -version

  • Step 2: Create a new Maven Project

To create a Maven project, you must install the Maven Plugin, yet, in the latest versions of Eclipse, it get installed already.

  • Step 3: Add Maven Dependencies to your project

In this step, you get to add several dependencies to your project. Navigate to thepom.xmlfile in the folder construction and so add the next dependencies & # 8211; Cucumber Java, Cucumber JUnit, JUnit, and Selenium Java. You can get these dependencies fromMaven Repository.

  • Step 4: Create a characteristic file

Navigate tosrc/test/resourcesin the folder structure and so create a feature pamphlet. Also, add a characteristic file in the feature folder there.

  • Step 5: Install the Cucumber Plugin

You can easy establish the Cucumber plugin from the Eclipse marketplace. The Cucumber plugin lets the codebase cognize that you ’ re create a Cucumber project.

  • Step 6: Create Step Definitions

To create Step definitions, navigate to the src/test/java package and then add a step definition folder and file thither.

  • Step 7: Create a Runner Class

Create a form file in the Step Definitions folder and add the runner class script. The runner class will look something like this.

meaning org.junit.runner.RunWith;
signification io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;

@ RunWith (Cucumber.class)
@ CucumberOptions (features= & # 8221; src/test/resources/Features & # 8221;,
glue= {& # 8220; StepDefinitions & # 8221;})
public class TestRunner {

}

What are Cucumber Annotations

Annotations in Cucumber are predefined texts that moderate some meaning for the compiler for the execution. In this subdivision, let us plunge a little deeper and understand hooks, rag, and more.

Also Read:

How to use Cucumber Tags

Tags are used to associate a tryout with a exceptional scenario.

For representative, there are multiple characteristic files containing respective scenarios. However, if you require to test only a few scenarios out of all the scenario from all the feature files, the wildcat force way unite all the required scenarios in one feature file and then executes it from the tryout runner class. However, this method becomes a headache and does not bring flexibility. Therefore, tags in such cases come in handy, separating multiple scenario and execute the required ones only.

Tags are the names that you give to the scenario in the feature file. To designate a name, you have to use the ‘ @ ’ symbol before writing the name. For example, to assign a scenario smoking test, use @ smoke in the lineament file right above the scenario you want to call.

@ name_of_the_test

Scenario: Define the scenario

Let ’ s take a practical example to understand how to use cucumber tags.

  • Create a Feature File

@Smoke

Feature: Feature to demo tags

Scenario: Example 1
Given
When
And

  • Create Step Definitions

Here, let us create a sample footstep definition file, where you will bind the necessary code with the scenario in the feature file.

  • Create a Test Runner Class

In the below trial, the scenario is marked with @ SmokeTest, therefore, in the test runner class file, you will assign those tag names that you want to run.

@ RunWith (Cucumber.class)
@ CucumberOptions (
features= & # 8221; src/test/resources/Features & # 8221;,
glue= {& # 8220; StepDefinition & # 8221;},
tags = {& # 8220; @ SmokeTest & # 8221;}
)

public class TestRunner {
}

  • If you receive created multiple scenarios, then the above test runner course file will allow the execution of only that code but that matches the name you have provided inside the ‘ tags ’ script.
  • To action various scenarios, you must use ‘ OR ’ keyword while writing the name of the scenarios you want to use inside the ‘ tags ’ script. For example, to accomplish all the scenarios that are marked with either @ Smoke or @ Regression, add tags = {& # 8220; @ Smoke OR @ Regression & # 8221;}.
  • Similarly, the ‘ AND ’ keyword is used when you have to accomplish scenarios that contain both keywords. For instance, in tags = {& # 8220; @ Smoke AND @ Regression & # 8221;} it will execute scenario that contain both names.
  • Use the ‘ NOT ’ keyword to ignore the scenarios that you desire to skip from getting execute.

Read More:

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

What are Hooks in Cucumber

Hooks in Cucumber are special blocks of code that run before or after each scenario. They grant you to manage frame-up and teardown actions or control specific parts of your.

The primary intent of enforce maulers is to reduce code gemination by setting up exceptional scripts as reusable code block. A hook can be defined anyplace throughout the project; however, it is placed in a separate brochure for better organization and maintainability.

How to use Cucumber Hooks

Consider a situation where you are creating multiple scenario, however, while writing the scenario you notice that before or after the executing of each scenario some sets of activity are the same. Therefore to prevent the recur use of the like code, crotchet are used. Hooks are the blocks of code that run before or after each scenario.

Also Read:

To define hooks, you must use notation like @ Before and @ After. There are three case of hooks in Cucumber & # 8211; Scenario, Step, and Conditional. Scenario Hooks run before and after each scenario. Step Hooks run before and after each step. Conditional Hooks are linked with tags for conditional execution.

The idea behind implementing hook is to manage the setup & amp; teardown and let better maintenance of codification.

  • Create a Feature File
@ RegressionTest Feature: Feature to Hooks Scenario: Example 2 Given When Then
  • Create Step Definitions

Create the necessary stride definitions file required for your project.

  • Create a Class for Hooks

Create a Java class for hooks. Note that, you must create this hooks class file inside the Step Definitions bundle.

package StepDefinitions; import io.cucumber.java.After; import io.cucumber.java.Before; public class Hooks {@ Before // write codification hither which you want to be executed before each scenario} @ After // compose code here which you need to be executed after each scenario}
  • Create a Test Runner Class
package cucumberOptions; importation org.junit.runner.RunWith; significance io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; @ RunWith (Cucumber.class) @ CucumberOptions (features= '' src/test/java/Features '', glue= '' StepDefinitions '', tags= '' @ RegressionTest '') public class TestRunner {}

When to Use Cucumber Hooks

Cucumber Hooks are all-important to manage the lifecycle of the quiz project effectively. However, to further level up the efficiency one must be mindful of when to use Cucumber Hooks to create maintainable and utile tests.

  • For Setup: A Before sweetener is employ to cook the test environs, including launching a browser, initializing database connections, and lots more.
  • For Tear Down: An After hook can be habituate to clean up after the test, such as fold the browser, clearing cookies, and much more.
  • Wrap up a scenario: An Around Hook can be used to envelop an entire scenario with custom logic, such as to enable or disable features for specific tests.
  • Creating Reports: Hooks are likewise used for creating reports or logging details about a failed test. This is useful for debug purposes.

Like what you are say?

You can get discussing with our discord community

What are the different types of Cucumber Hooks?

In a test execution lifecycle, there are several instances where one is required to use crotchet to reduce code duplication, enhance maintainability, and write an effective test script.

Cucumber provides various type of maulers, and hither are different types of cuke hook.

1. Before Hook

The Before hook is executed before each. Therefore, it is generally used to initialise the tryout scenario and configure resources necessitate for the test, such as launch the browser before each scenario, setting up database connections, calling APIs, and more.

const {Before} = require (' @ cucumber/cucumber '); Before (function () {console.log (`` Setting up the environment before the scenario '');});

2. After Hook

The After lure is executed after each test scenario; therefore, it is broadly used to reset the environment to its previous state. It is also used in cleanup tasks such as closing the browser illustration, deleting examination information, and more.

const {After} = require (' @ cucumber/cucumber '); After (function () {console.log (`` Cleaning up the environment after the scenario '');});

3. BeforeStep Hook

The BeforeStep lure is accomplish before each individual step, hence, it is generally apply for step-level initialization or logging.

const {BeforeStep} = require (' @ cucumber/cucumber '); BeforeStep (function () {console.log (`` Before executing the footstep '');});

4. AfterStep Hook

The AfterStep crotchet is executed after each individual step. Therefore, it is generally used for capturing screenshots and cleaning up temporary data.

const {AfterStep} = require (' @ cucumber/cucumber '); AfterStep (function () {console.log (`` After execute the step '');});

5. Tagged Hooks

These hooks are useful for execute specific crotchet only on scenarios equipped with particular tags. They are useful for applying usance logic to certain scenario without affecting others.

const {Before, After} = require (' @ cucumber/cucumber '); // Run this come-on before scenarios label with @ smoke Before ({tags: `` @ smoking ''}, office () {console.log (`` Setup for fume examination '');});

6. Around Hook

It is a useful Cucumber sweetener in wrapping around a scenario to run a specific code both before and after the scenario ’ s execution. It handles total control by running any conditional codification around a single test scenario.

const {Around} = require (' @ cucumber/cucumber '); Around (function (runScenario) {console.log (`` Starting the scenario ''); runScenario (); console.log (`` Ending the scenario '');});

Also Read:

How to Run Hooks

In the test lifecycle, Hooks are executed mechanically without any requirement for additional commands. Cucumber automatically detects them and runs them at delineate points. Here ’ s how to set up hooks and run Hooks in Cucumber.

  1. Define hooks in a separate file for better code maintenance.
  2. Import Hooks in the exam file. The cucumber mechanically detects Hooks if placed in the like directory as the test file.
  3. Execute the examination suite using the following command.
mvn test

How to Use the ‘ Background ’ Keyword

Tags and Hooks afford an overview of Cucumber Annotations. Now, let ’ s look at one more crucial keyword which facilitate in better the overall maintainability of our codification. Background keyword is a radical of steps that are mutual to all the scenarios in a feature. It is specify once and for all in the project. It improve the readability and reusability of the code and prevents repeating steps in every scenario.

Moreover, It is pretty similar to hooks however, the background is seeable in the lineament file.

Now, let ’ s realise how to use the ‘ ground ’ keyword with the helper of an example.

  • Create a Feature File

Feature: Test bstackdemo

Scenario: Check & # 8216; Add to Cart & # 8217; push
Given user is logged in
When exploiter clicks on & # 8216; Add to Cart & # 8217; push
Then product is displayed in the go-cart

Scenario: Check & # 8216; Favorite & # 8217; button is working
Given user is logged in
When exploiter clicks on & # 8216; Favorite & # 8217; push
Then product is exhibit in the & # 8216; Favorites & # 8217; page

In the above characteristic file, it can be distinctly seen that the same Given stride is used for two scenarios. Therefore, let us make a common step with the help of the ‘ ground ’ keyword. The new lineament file will look like this.

Feature: Test bstackdemo
Background:

Given exploiter is log in

Scenario: Check & # 8216; Add to Cart & # 8217; push
When user clicks on & # 8216; Add to Cart & # 8217; button
Then product is display in the cart

Scenario: Check & # 8216; Favorite & # 8217; push is working
When user dog on & # 8216; Favorite & # 8217; push
Then product is display in the & # 8216; Favorites & # 8217; page

After this, create the necessary Test Runner class and Step Definitions for the feature file and you ’ re good to go running a successful tryout using the ‘ ground ’ keyword.

Cucumber is an amazing testing framework that supports BDD (Behavior Driven Development). It proffer various tools that facilitate our testing experience. Cucumber supports several programming languages allowing users to be more elastic.

You can use Cucumber with popular automation frameworks like Selenium and Cypress. Testing on a real device cloud gives you the advantage of identifying all the issues faster and in a more unlined manner. BrowserStack proffer a real device cloud platform that allows you to run your tests on a combination of 3500+ device, browsers, and function systems.

Talk to an Expert

What is the difference between Background and Hooks in Cucumber?

Background and hooks are robust mechanism in Cucumber that let execute shared or pre-defined logic in different scenarios. Having said that, they serve different purposes and are leveraged in different circumstance. Here are the main differences between Background and Hooks in Cucumber.

BackgroundHooks
Background keyword is a group of steps that are common to all the scenario in a feature. It is delineate once and for all in the project. It improves the readability and reusability of the code and prevents repeating steps in every scenario.Hooks allow you to manage setup and teardown activeness or control specific parts of your test execution.
Background focus on specify the steps that come across during execution.Hooks focuses on the execution of the code.
The Background is strictly limited to gherkin setups and doesn ’ t work with non-gherkin setups.Hooks can manage complex setups such as call APIs, handling complex databases, and lots more. Therefore, Hooks are more flexible than Background.

Conclusion

In software testing, Hooks play an essential role in managing the setup and tear-down logic. Moreover, it is also useful in executing conditional logic for specific playscript without impact the other elements of the test. Their ability to go along with the ticket grant them to execute scripts for selective applications, which is a versatile feature in mechanization testing.

You can use Cucumber with democratic automation frameworks like Selenium and Cypress. Testing on a real device cloud gives you the reward of identifying all the issues faster and in a more seamless manner.

BrowserStack volunteer a existent twist cloud program that allows you to run your tests on a combination of 3500+ device, browsers, and operating scheme.

Useful Resources

Tags
86,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free