In Cucumber, the Step Definition file is where the actual code implementation of test steps written in the Feature file (in Gherkin syntax) resides. It acts as a bridge between the plain-text behavior scenarios and the underlying automation code.
What is a Step Definition File?
A Step Definition file contains methods/functions that define how each step in the Gherkin Feature File should be executed. These methods are annotated with Cucumber expressions or regular expressions that match the steps written in the feature file.
Purpose of Step Definitions
Connects Gherkin steps to Java/Python/Ruby code
Enables automation of behaviors described in the feature file
Promotes code reuse across multiple scenarios
Separates test logic from test documentation
Given user is on the login page
@Given("user is on the login page") public void user_is_on_login_page() { // Code to launch browser and navigate to login page }
Step Definition Syntax (Java Example)
Annotations used:
@Given@When@Then@And@But
Example:
Feature File:
Feature: Login feature Scenario: Valid login Given user is on the login page When user enters valid username and password Then user should be redirected to homepage
public class LoginSteps { @Given("user is on the login page") public void user_is_on_login_page() { System.out.println("User is on login page"); // Code to open browser and load login page } @When("user enters valid username and password") public void user_enters_credentials() { System.out.println("User enters credentials"); // Code to enter username and password } @Then("user should be redirected to homepage") public void user_redirected_to_homepage() { System.out.println("Redirected to homepage"); // Code to verify successful login } }
Guidelines for Writing Step Definitions
Match steps precisely using regex or Cucumber expressions
Avoid duplicate step definitions
Use parameterization for dynamic data (e.g., usernames)
Keep methods short and focused
Feature:
When user logs in with username "john" and password "12345"
@When("user logs in with username {string} and password {string}") public void user_logs_in(String username, String password) { // Use username and password in automation script }
Location of Step Definition Files
Typically placed under
src/test/java/stepDefinitionsor a similar structureThe '
glue'property in the@CucumberOptionsannotation tells Cucumber where to find these files
@CucumberOptions( features = "src/test/resources/features", glue = "stepDefinitions" )
| Attribute | Description |
|---|---|
| Purpose | Connects Gherkin steps to executable code |
| Contains | Methods annotated with @Given, @When, @Then etc. |
| Languages | Java, Python, Ruby, JavaScript, etc. |
| Parameter Support | Yes, using Cucumber expressions or regex |
| Best Practice | Keep reusable, simple, and DRY (Don't Repeat Yourself) |