What are annotations in Cucumber?

Annotations in Cucumber are predefined keywords or text that hold a specific meaning and help the framework understand what should be done upon execution. They allow you to enhance and customize the behavior of your Cucumber tests. The main annotations in Cucumber are:

Tags

Tags are used to uniquely identify scenarios in feature files. They allow you to selectively run or exclude specific scenarios based on the tags applied to them. Tags are defined using the @ symbol followed by a name, placed above the scenario.

Example:

@smoke
Scenario: Login with valid credentials
  Given I am on the login page
  When I enter valid username and password
  Then I should be logged in

Hooks

Hooks are blocks of code that can be executed before or after scenarios, steps, or other parts of the test execution. They allow you to set up preconditions or perform cleanup tasks. Some commonly used hooks are:

  • @Before: Runs before each scenario
  • @After: Runs after each scenario
  • @BeforeStep: Runs before each step
  • @AfterStep: Runs after each step

Example:

@Before
public void setup() {
  // Set up test environment
}

@After
public void teardown() {
  // Clean up test environment
}

Background

The Background keyword is used to define a set of steps that should run before each scenario in a feature file. It helps avoid repetition of common steps across multiple scenarios.

Example:

Feature: Login

  Background:
    Given I am on the login page

  Scenario: Login with valid credentials
    When I enter valid username and password
    Then I should be logged in

  Scenario: Login with invalid credentials  
    When I enter invalid username and password
    Then I should see an error message

These annotations, along with the Gherkin syntax (Given, When, Then, And, But), help make Cucumber tests more expressive, maintainable, and adaptable to changing requirements.

Author: learnwithdey