Data Table in Cucumber Framework

In Cucumber, DataTables are used to pass multiple values or structured data from a feature file to step definitions.

They help:

     1. Avoid repeating steps for similar data
     2. Pass structured test data (like form fields, user details, etc.)
     3. Simplify test maintenance

Syntax in Feature File

A step followed by a table becomes a DataTable:

And add the customers with mandatory fields

  | Username |
  | tester   |
  | tester1  |
  | tester2  |


Use Cases of DataTables

Cucumber lets you work with DataTables in several formats depending on the structure of the table.

1. Single Column (List)

Use this when there is only one column of data

And add the customers with mandatory fields

  | Username |
  | tester   |
  | tester1  |
  | tester2  |


Step Definition:

@And("add the customers with mandatory fields")
public void addCustomersWithMandatoryFields(DataTable dt) {
    List<String> users = dt.asList();
    for (String username : users) {
        System.out.println("Creating user: " + username);
    }
}


2. Multiple Rows with Headers (List of Maps)

Use this when there are multiple columns with headers — each row is a separate record.

And add the customers with mandatory fields
  | Username | Lastname | Postcode |
  | tester   | one      | 1111     |
  | tester1  | two      | 2222     |
  | tester2  | three    | 3333     |


Step Definition

@And("add the customers with mandatory fields")
public void addCustomersWithFields(DataTable dt) {
    List<Map<String, String>> data = dt.asMaps(String.class, String.class);
    for (Map<String, String> user : data) {
        String username = user.get("Username");
        String lastname = user.get("Lastname");
        String postcode = user.get("Postcode");
        System.out.println("Creating user: " + username + " " + lastname + " - " + postcode);
    }
}


Use this when you want to access specific rows and columns.

@And("add the customers with mandatory fields")
public void addCustomersWithSpecificCell(DataTable dt) {
    System.out.println("Row 1, Col 1: " + dt.cell(1, 0));  // tester
    System.out.println("Row 2, Col 2: " + dt.cell(2, 1));  // two
}


Note: cell(rowIndex, columnIndex) is zero-based, except header row is always row 0.

Supported Data Formats in Java Step Definitions

Table Format 

Java Collection Type

Single Column

List<String>

Multiple Columns, No Headers

List<List<String>>

Rows with Headers

List<Map<String, String>>

Vertical Headers

Map<String, String>

Nested Map

Map<String, Map<String, String>>

 

Related Tutorials