What are Hooks in Cucumber?

  

What are Hooks in Cucumber?

Hooks in Cucumber are blocks of code that run before or after each scenario or step in your test suite. They are used to setup and teardown test environments. Hooks are written in the Step Definition file using annotations like:

  • @Before

  • @After

  • @BeforeStep

  • @AfterStep


These come from io.cucumber.java, and are similar to setup and teardown methods in testing frameworks like JUnit or TestNG.


Why Use Hooks?

Hooks are useful for:

  • Launching a browser before each test

  • Logging into a system

  • Setting up test data

  • Cleaning up after test execution

  • Capturing screenshots on failure


Types of Hooks

HookDescription
@BeforeRuns before each scenario
@AfterRuns after each scenario
@BeforeStepRuns before each step (rarely used)
@AfterStepRuns after each step (example: take screenshot)


Hook Execution Order

You can control the order using the order parameter:

@Before(order = 1)
public void setupDB() {}

@Before(order = 2)
public void setupBrowser() {}

Lower order values run first.


Example: Cucumber Hooks in Java

1. Feature File:

Feature: Login Feature

  Scenario: Successful login
    Given user is on login page
    When user enters valid credentials
    Then user is redirected to home page




2. Step Definition File (LoginSteps.java):

package stepdefinitions;

import io.cucumber.java.en.*;

public class LoginSteps {

    @Given("user is on login page")
    public void user_is_on_login_page() {
        System.out.println("User is on login page");
    }

    @When("user enters valid credentials")
    public void user_enters_valid_credentials() {
        System.out.println("User enters valid credentials");
    }

    @Then("user is redirected to home page")
    public void user_is_redirected_to_home_page() {
        System.out.println("User is redirected to home page");
    }
}




3. Hook File (Hooks.java):

package stepdefinitions;

import io.cucumber.java.Before;
import io.cucumber.java.After;

public class Hooks {

    @Before
    public void beforeScenario() {
        System.out.println("==== Launching browser before scenario ====");
    }

    @After
    public void afterScenario() {
        System.out.println("==== Closing browser after scenario ====");
    }
}



Output:

==== Launching browser before scenario ====
User is on login page
User enters valid credentials
User is redirected to home page
==== Closing browser after scenario ====

How to use Cucumber with Selenium

  

How to Integrate Cucumber with Selenium in Java?

Cucumber is a testing framework that supports Behavior-Driven Development (BDD), which allows writing test cases in natural language using Gherkin syntaxSelenium is used for automating web applications. Together, they help in writing BDD-style automation tests for web applications.


Below is the Step-by-Step Integration of Cucumber with Selenium in Java.


Prerequisites to write this code:

  • Java installed

  • Maven or Gradle (we’ll use Maven)

  • IDE (e.g., IntelliJ or Eclipse)


1. Maven Project Setup


Below are pom.xml dependencies:
<dependencies>
    <!-- Cucumber -->
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>7.14.0</version>
    </dependency>
    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>7.14.0</version>
        <scope>test</scope>
    </dependency>

    <!-- Selenium -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.20.0</version>
    </dependency>

    <!-- JUnit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>



2. Directory Structure


src/test/java ├── features │ └── Login.feature ├── stepdefinitions │ └── LoginSteps.java ├── runners │ └── TestRunner.java └── pages └── LoginPage.java

Below is the feature file to write plain english scenario using gherkin keywords under feature.

3. Login.feature


Feature: Login functionality

  Scenario: Successful login with valid credentials
    Given User is on the login page
    When User enters valid username and password
    And clicks the login button
    Then User should be redirected to the home page


Below is page class which is implemented in selenium java for writing web page automation
logic.


4. LoginPage.java

package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class LoginPage {
    WebDriver driver;

    public LoginPage(WebDriver driver) {
        this.driver = driver;
    }

    By username = By.id("username");
    By password = By.id("password");
    By loginBtn = By.id("login");

    public void enterUsername(String user) {
        driver.findElement(username).sendKeys(user);
    }

    public void enterPassword(String pass) {
        driver.findElement(password).sendKeys(pass);
    }

    public void clickLogin() {
        driver.findElement(loginBtn).click();
    }
}


Below is step definition class which is implemented in selenium java for implementing
feature file steps in the form of java codes.

5. LoginSteps.java

package stepdefinitions;

import io.cucumber.java.en.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import pages.LoginPage;

public class LoginSteps {
    WebDriver driver;
    LoginPage login;

    @Given("User is on the login page")
    public void user_on_login_page() {
        driver = new ChromeDriver();
        driver.get("https://example.com/login");
        login = new LoginPage(driver);
    }

    @When("User enters valid username and password")
    public void user_enters_credentials() {
        login.enterUsername("testuser");
        login.enterPassword("password123");
    }

    @When("clicks the login button")
    public void click_login_button() {
        login.clickLogin();
    }

    @Then("User should be redirected to the home page")
    public void user_on_home_page() {
        String title = driver.getTitle();
        assert title.contains("Home");
        driver.quit();
    }
}


Below is the Test runner java class implemented in cucumber with testng to run
the script.


6. TestRunner.java

package runners;

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

@RunWith(Cucumber.class)
@CucumberOptions(
    features = "src/test/java/features",
    glue = {"stepdefinitions"},
    plugin = {"pretty", "html:target/cucumber-report.html"},
    monochrome = true
)
public class TestRunner {
}


Running the Test

  • Right-click TestRunner.java → Run as JUnit Test

  • It will execute the steps in the feature file using Selenium


Summary

ComponentRole
feature fileDefines scenarios in plain English
Step DefinitionsLinks Gherkin steps to Selenium actions
Page ClassRepresents elements using POM
TestRunnerCucumber JUnit runner

How Cucumber is useful in BDD

  

Cucumber is highly useful in software testing, especially when following the Behavior Driven Development (BDD) approach. Here's a detailed explanation of how and why Cucumber is useful:


What is Cucumber?

Cucumber is an open-source BDD testing tool that allows you to write test cases in plain English using a language called Gherkin. These test cases describe how the application should behave from the user's perspective.


How Cucumber is Useful in Testing

1. Bridges Communication Gap

  • Non-technical stakeholders (like business analysts or clients) can understand test cases because they are written in plain English.

  • Developers, testers, and business stakeholders can all collaborate more effectively.


2. Readable Test Scenarios with Gherkin

  • Cucumber uses the Gherkin syntax, which is easy to read and write:

Scenario: Successful login with valid credentials
  Given the user is on the login page
  When the user enters valid credentials
  Then the user should be redirected to the dashboard



3. Supports Test Automation

  • Cucumber can be integrated with Selenium, Appium, REST Assured, etc., for automating web, mobile, and API testing.

  • Each Gherkin step can be linked to a step definition written in code (Java, Python, Ruby, etc.).



4. Ensures Behavior Matches Requirements

  • Since scenarios are written based on requirements, they ensure that actual behavior matches expected behavior.

  • Great for regression testing – you can easily rerun scenarios to check for bugs.



5. Improves Test Coverage

  • Forces teams to think about real-world scenarios, improving functional test coverage.

  • Helps in identifying edge cases and business rules early.


6. Living Documentation

  • Cucumber scenarios act as live, always up-to-date documentation for the system.

  • Easy to trace from requirement → test case → implementation.



7. Reusable Steps

  • Step definitions can be reused across multiple scenarios, reducing duplication and maintenance.



Integrations & Ecosystem

  • Works with many test runners (JUnit, TestNG).

  • Integrates with CI/CD tools like Jenkins, GitLab CI, GitHub Actions, etc.

  • Supports multiple programming languages – Java, Ruby, JavaScript, Python, etc.



Example Use Case

Imagine a banking app:

  • Business analyst writes scenarios like:

Scenario: Transfer money between accounts
Given the user has $500 in checking
When the user transfers $100 to savings
Then the checking account should have $400


Developers and testers implement automation using this scenario, ensuring clear communication and fast feedback.


Points to remember:

FeatureBenefit
Gherkin syntaxEasy for non-programmers to understand
Behavior-Driven DevelopmentAligns tests with business goals
Reusability of stepsEfficient maintenance and consistency
Test Automation SupportIntegrates with tools like Selenium/Appium
Living documentationKeeps tests and requirements aligned
CI/CD IntegrationSupports continuous testing and delivery

What is Cucumber Framework?

  

Cucumber is one of the most popular tools used for Behavior Driven Development (BDD). It allows developers, testers, and business analysts to write test cases in a natural, human-readable language that bridges the gap between technical and non-technical stakeholders.


What is Cucumber ?

Cucumber is an open-source BDD testing tool written in Ruby, but it supports many languages like Java, JavaScript, Python, and others. It enables you to write executable specifications for software behavior using a plain text language called Gherkin.

These Gherkin scenarios are then mapped to step definitions, which are actual automation code written in a programming language like Java or Python.


Why Use Cucumber?

  • Encourages collaboration between developers, testers, and business users.

  • Helps in defining clear acceptance criteria.

  • Makes test cases more understandable to non-technical stakeholders.

  • Acts as documentation of the system’s behavior.

  • Supports automation and manual readability together.


Example of Cucumber in BDD

Gherkin Feature File - login.feature

Feature: Login Functionality

  Scenario: Successful login with valid credentials
    Given the user is on the login page
    When the user enters a valid username and password
    And clicks on the login button
    Then the user should be redirected to the homepage



Step Definition file - Java class

@Given("the user is on the login page")
public void user_on_login_page() {
    // Code to open login page
}

@When("the user enters a valid username and password")
public void enter_credentials() {
    // Code to enter username and password
}

@When("clicks on the login button")
public void click_login_button() {
    // Code to click login button
}

@Then("the user should be redirected to the homepage")
public void redirect_to_homepage() {
    // Code to verify homepage
}




Features of Cucumber

FeatureDescription
Gherkin LanguageUses plain English-like syntax (Given-When-Then) to write scenarios.
Supports Multiple LanguagesWorks with Java, Ruby, Python, JavaScript, etc.
Readable by Non-Technical UsersDesigned to be easily understood by business stakeholders.
Integration with Selenium and Other ToolsWorks well with automation tools like Selenium, Appium.
ReusabilityStep definitions can be reused across multiple scenarios.
TagsHelps in grouping and selectively running scenarios.
HooksAllows setting up @Before and @After actions for scenarios.
ReportsSupports various report formats like HTML, JSON, etc.
Parallel ExecutionAllows running scenarios or features in parallel for faster testing.
Live DocumentationFeature files serve as live documentation of the system.


Advantages of Cucumber

  • Readable and easy to write test scenarios.

  • Encourages collaboration among teams.

  • Facilitates automated acceptance testing.

  • Promotes test-first approach in Agile and BDD.


Disadvantages of Cucumber

  • May add overhead for small projects.

  • Requires learning curve for writing Gherkin properly.

  • May lead to duplicate steps if not managed well.

  • Execution is slower compared to unit test frameworks.

Maven Build Automation

  


What is Build Automation in Maven ?

Build Automation in Maven refers to the automatic handling of the build lifecycle—compiling code, running tests, packaging, installing, and deployingespecially when multiple projects depend on one another.


Maven and Project Dependencies

In many real-world applications, software is split into modules or multiple Maven projects, where one project (child) depends on another (parent or dependency).


For example:

Project A (Core Library)
Project B (Depends on A)


When you change and build Project AProject B should automatically be rebuilt using the updated version of A. Maven handles this automation.


How Maven Automates Builds for Dependent Projects

1. Using mvn install to Install Artifacts

  • When you run mvn install in Project A, Maven:

    • Compiles the source code.

    • Packages it (JAR/WAR).

    • Installs it into the local repository (~/.m2/repository).

  • Now, any project like Project B, which depends on A, can fetch this artifact from the local repository.



2. Declaring Dependencies in pom.xml

Project B’s pom.xml declares:


<dependencies>
  <dependency>
    <groupId>com.example</groupId>
    <artifactId>project-a</artifactId>
    <version>1.0-SNAPSHOT</version>
  </dependency>
</dependencies>



Maven will now:

  • Automatically fetch and include Project A’s build.

  • Recompile Project B if Project A is updated and reinstalled.



Multi-Module Project Automation (Advanced)

If Projects A and B are part of a multi-module Maven project, Maven will:

  • Automatically build modules in the correct order based on dependencies.

  • Avoid needing manual builds/install for each module.


Parent pom.xml:

<modules>
  <module>project-a</module>
  <module>project-b</module>
</modules>


Maven will:

  • Build project-a first.

  • Then build project-b after project-a is available.




Benefits of Maven Build Automation for Dependencies


BenefitDescription
EfficiencyRebuilds only what's changed.
Dependency ManagementAutomatically pulls dependent artifacts.
ConsistencyEnsures consistent versioning across builds.
Local/Remote Repo UseBuilds can pull from local/remote repositories.
Tool IntegrationWorks with Jenkins, CI/CD, IDEs, etc.



Example Workflow

  • Modify code in Project A.
  • Run mvn install in Project A → Installs updated JAR in local repo.
  • Run mvn clean install in Project B → Maven automatically picks updated A.
  • All dependent builds are consistent and automated.