Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Scenario Outlines and Data

Data Tables in Steps

Pass structured data to a Cucumber step with data tables: the DataTable API, lists of maps, key-value tables, custom @DataTableType conversion to objects and table diffs.

Some steps need more than a number or a word. "Given the shop stocks these products" really means a list of products, each with a name, a price and a quantity. A data table attached to a step carries that information in a form everybody can read at a glance:

GHERKIN
Scenario: Totals in a mixed cart
  Given the shop stocks these products
    | name   | price | stock |
    | Book   | 12    | 10    |
    | Lamp   | 30    | 3     |
    | Mug    | 6     | 25    |
  When the customer buys 1 "Lamp" and 2 "Mug"
  Then the order total is 42 dollars

The table sits under the step that uses it, indented, with columns separated by |. It becomes an extra, last argument of the step definition.

The DataTable argument

Java
import io.cucumber.datatable.DataTable;

@Given("the shop stocks these products")
public void theShopStocks(DataTable table) {
    List<Map<String, String>> rows = table.asMaps();
    for (Map<String, String> row : rows) {
        shop.stock(row.get("name"),
                   Integer.parseInt(row.get("price")),
                   Integer.parseInt(row.get("stock")));
    }
}

DataTable has several views of the same grid:

Method Result When to use
asMaps() List<Map<String,String>>, header row = keys Tables with a header row
asMap() Map<String,String> from two columns Vertical key-value tables
asList() List<String> from a one-column table A simple list of values
asLists() List<List<String>> including the header Raw rows
asMaps(String.class, Integer.class) Typed values Convert cells while reading
transpose() New table, rows and columns swapped Horizontal data layouts
diff helpers (assertEquals) Compares two tables Then steps that check lists

You can also ask the step to receive typed objects directly: List<Product>, with a registered table type (below), instead of a raw DataTable.

Shapes of table

List of records (header row)

GHERKIN
| name | price |
| Book | 12    |
| Lamp | 30    |

Read with asMaps() or as List<Product>.

Single column list

GHERKIN
| Book |
| Lamp |

Read with asList().

Key-value pairs (vertical)

GHERKIN
| name     | Maria |
| plan     | gold  |
| country  | DE    |

Read with asMap() (first column keys, second values).

Horizontal records (one record per column) are read by calling transpose() first and then using the first shape.

Parsing a table: a stand-in

Here is a stand-in that parses a pipe table into the same List<Map<String,String>> structure Cucumber gives you, then uses it to stock a shop and compute an order total. The parse method also trims cells and handles an escaped pipe.

Java Stand-in: a DataTable as a list of maps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Custom table types: from rows to objects

Working with Map<String,String> and manual parsing becomes noisy. Cucumber lets you register a table entry transformer and then receive typed lists directly. In Cucumber-JVM this is @DataTableType:

Java
public record Product(String name, int price, int stock) {}

public class TableTypes {
    @DataTableType
    public Product product(Map<String, String> entry) {
        return new Product(
            entry.get("name"),
            Integer.parseInt(entry.get("price")),
            Integer.parseInt(entry.get("stock")));
    }
}
Java
@Given("the shop stocks these products")
public void theShopStocks(List<Product> products) {
    products.forEach(shop::stock);
}

Behind the scenes Cucumber reads the table with asMaps() and calls your product method per row. The same mechanism works for a single column (@DataTableType with a String argument), for rows as lists (List<String> argument) or a whole table. For simple records, recent versions can even map columns to constructor parameters or fields automatically.

The stand-in below mimics @DataTableType: a registry of entry converters is looked up by the target type, so the step receives a List<Product>.

Java Stand-in: a table entry converter producing records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Tables in Then steps: comparing lists

Data tables also express expected collections:

GHERKIN
Then the cart contains
  | name | quantity | line total |
  | Lamp | 1        | 30         |
  | Mug  | 2        | 12         |

The step compares the table with the actual cart. Do not loop and assertEquals field by field; convert actual data to a comparable form and compare once, so the failure message shows both lists. DataTable.diff-style helpers produce a readable report. The stand-in below compares expected and actual rows and prints a diff, marking missing, unexpected and changed lines.

Java Stand-in: comparing an expected table with actual rows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Design advice

  • Choose the shape that matches the data: a list of records for entities, key-value for one object, a single column for a list of strings.
  • Name columns in the domain's language (line total, not col3).
  • Keep tables small. Past ten rows consider whether a file, a fixture or a unit test is a better home.
  • Align the pipes; many editors have a feature to format Gherkin tables.
  • Avoid hidden columns. If every step needs id, created, flags, then the table is a database dump; show only the columns that explain the outcome.
  • Distinguish from Examples tables: Examples vary a whole scenario; step tables feed one step (see scenario outlines).

Long free text is a different case: use a doc string, next: doc strings.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does a step's data table appear in the feature file?

    The table is indented beneath its step and becomes the last argument of the step definition.
  2. 2. Which DataTable method reads a table with a header row into a list of records?

    asMaps() returns a List<Map<String,String>> keyed by header names.
  3. 3. What does @DataTableType do?

    It maps rows or cells to your own types, keeping parsing out of the step body.
  4. 4. What is the main difference between an Examples table and a step data table?

    Examples tables create several scenarios; step tables carry structured data into a single step.

Summary

  • A data table under a step passes structured data as a DataTable (or a typed list).
  • Pick the right view: asMaps, asMap, asList, asLists, transpose.
  • @DataTableType converts rows to your own types so steps stay short.
  • Use tables in Then steps to compare expected and actual collections in one assertion.
  • Keep tables small, readable and in domain vocabulary.

Next: Doc Strings