Parameterization

In the previous chapter we have learned how to create a feature file with multiple scenario and how to create step definition file and create a connection between them. In this chapter we will learn how to parameterize the steps with different values.


Let's update our previous feature file to include the username and password in the step with When keyword. The updated feature file will look as the following.


Gherkin
Copy
Feature: Login functionality
  Scenario: Successful login
    Given the user is on the login page
    When the user enters username "root" and password "admin"
    Then the user should be logged in successfully

  Scenario: Invalid login attempts
    Given the user is on the login page
    When the user enters username "root" and password "pass"
    Then the login should fail with an error message

Since we have updated the When statement in both scenario, we need to update the step definition file for both. Fortunately the best part of cucumber is that we do not need to create two step definition function, rather we can create one for both. Let's understand this by following step definition file.


Java
Copy
@Given("the user is on the login page")
public void navigateToLoginPage() {
	// Code to navigate to the login page
	System.out.println("User is on the login page");
}

@Then("the user should be logged in successfully")
public void verifySuccessfulLogin() {
	// Code to verify successful login
	System.out.println("User is logged in successfully");
}

@Then("the login should fail with an error message")
public void verifyLoginFailure() {
	// Code to verify login failure with an error message
	System.out.println("Login failed with an error message");
}

@When("the user enters username {string} and password {string}")
public void theUserEntersUsernameRootAndPasswordAdmin(String username, String password)
{
	System.out.println("The user enters username " + username + " and password " + password + ".");
}

In the above example we have created a single function for two when statements. In the feature file we have passed hard coded parameters username as "root" and password as "admin". These were received by step definition file methods as {string}. Since the both the statement of When keyword from both scenario matches, we can use a common function for them.