Data Table in Cucumber

  

What are Data Tables in Cucumber?

In CucumberData Tables are used to pass structured data (like tabular format) to steps in a feature file. It allows you to supply multiple rows of input to a single step in a Gherkin scenario.

They are especially useful when you want to test a scenario using multiple sets of values for the same action without repeating the entire scenario.


Why Use Data Tables?

  • Makes test cases more readable and maintainable.

  • Allows passing multiple sets of data (rows and columns).

  • Avoids duplication of steps.

  • Makes your tests data-driven.




Types of Data Tables in Cucumber
  • One-Dimensional Data Table – like a list.
  • Two-Dimensional Data Table – like a table with headers.
  • Without Header – multiple rows but no column names.


1. Feature File with Data Table

Feature: Login Feature

  Scenario: Successful login with valid credentials
    Given the user enters the following credentials
      | username | password  |
      | john123  | pass123   |


 

2. Step Definition for Data Table (Java)

import io.cucumber.java.en.Given;
import io.cucumber.datatable.DataTable;
import java.util.List;
import java.util.Map;

public class LoginSteps {

    @Given("the user enters the following credentials")
    public void the_user_enters_the_following_credentials(DataTable dataTable) {
        List<Map<String, String>> credentials = dataTable.asMaps(String.class, String.class);

        for (Map<String, String> credential : credentials) {
            String username = credential.get("username");
            String password = credential.get("password");
            System.out.println("Username: " + username + ", Password: " + password);

            // Here you can call your login method or perform UI action
            // loginPage.login(username, password);
        }
    }
}


How it Works

  • DataTable is automatically passed to your step definition.

  • asMaps(String.class, String.class) converts each row into a Map where:

    • Key = column header

    • Value = cell value


You can use Data Tables in scenarios like:

  • Filling forms with multiple values

  • Testing multiple login credentials

  • Verifying entries in a shopping cart




Important Points:

FeatureDescription
Data TableStructured input passed to steps
FormatTabular (rows and columns)
ConversionUse .asList() or .asMaps()
Use CasesData-driven testing, repeated data input

No comments:

Post a Comment