eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Overview

Cucumber is a Behavioral Driven Development (BDD) framework that allows developers to create text-based test scenarios using the Gherkin language.

In many cases, these scenarios require mock data to exercise a feature, which can be cumbersome to inject — especially with complex or multiple entries.

In this tutorial, we’ll look at how to use Cucumber data tables to include mock data in a readable manner.

2. Scenario Syntax

When defining Cucumber scenarios, we often inject test data used by the rest of the scenario:

Scenario: Correct non-zero number of books found by author
  Given I have the a book in the store called The Devil in the White City by Erik Larson
  When I search for books by author Erik Larson
  Then I find 1 book

2.1. Data Tables

While inline data suffices for a single book, our scenario can become cluttered when adding multiple books.

To handle this, we create a data table in our scenario:

Scenario: Correct non-zero number of books found by author
  Given I have the following books in the store
    | The Devil in the White City          | Erik Larson |
    | The Lion, the Witch and the Wardrobe | C.S. Lewis  |
    | In the Garden of Beasts              | Erik Larson |
  When I search for books by author Erik Larson
  Then I find 2 books

We define our data table as a part of our Given clause by indenting the table underneath the text of the Given clause. Using this data table, we can add an arbitrary number of books — including only a single book — to our store by adding or removing rows.

Additionally, data tables can be used with any clause — not just Given clauses.

2.2. Including Headings

It’s clear that the first column represents the title of the book, and the second column represents the author of the book. The meaning of each column is not always so obvious, though.

When clarification is needed, we can include a header by adding a new first row:

Scenario: Correct non-zero number of books found by author
  Given I have the following books in the store
    | title                                | author      |
    | The Devil in the White City          | Erik Larson |
    | The Lion, the Witch and the Wardrobe | C.S. Lewis  |
    | In the Garden of Beasts              | Erik Larson |
  When I search for books by author Erik Larson
  Then I find 2 books

While the header appears to be just another row in the table, this first row has a special meaning when we parse our table into a list of maps in the next section.

3. Step Definitions

After creating our scenario, we implement the Given step definition.

In the case of a step that contains a data table, we implement our methods with a DataTable argument:

@Given("some phrase")
public void somePhrase(DataTable table) {
    // ...
}

The DataTable object contains the tabular data from the data table we defined in our scenario as well as methods for transforming this data into usable information. Generally, there are three ways to transform a data table in Cucumber: (1) a list of lists, (2) a list of maps and (3) a table transformer.

To demonstrate each technique, we’ll use a simple Book domain class:

public class Book {

    private String title;
    private String author;

    // standard constructors, getters & setters ...
}

Additionally, we’ll create a BookStore class that manages Book objects:

public class BookStore {
 
    private List<Book> books = new ArrayList<>();
     
    public void addBook(Book book) {
        books.add(book);
    }
     
    public void addAllBooks(Collection<Book> books) {
        this.books.addAll(books);
    }
     
    public List<Book> booksByAuthor(String author) {
        return books.stream()
          .filter(book -> Objects.equals(author, book.getAuthor()))
          .collect(Collectors.toList());
    }
}

For each of the following scenarios, we’ll start with a basic step definition:

public class BookStoreRunSteps {

    private BookStore store;
    private List<Book> foundBooks;
    
    @Before
    public void setUp() {
        store = new BookStore();
        foundBooks = new ArrayList<>();
    }

    // When & Then definitions ...
}

3.1. List of Lists

The most basic method for handling tabular data is converting the DataTable argument into a list of lists.

We can create a table without a header to demonstrate:

Scenario: Correct non-zero number of books found by author by list
  Given I have the following books in the store by list
    | The Devil in the White City          | Erik Larson |
    | The Lion, the Witch and the Wardrobe | C.S. Lewis  |
    | In the Garden of Beasts              | Erik Larson |
  When I search for books by author Erik Larson
  Then I find 2 books

Cucumber converts the above table into a list of lists by treating each row as a list of the column values.

So, Cucumber parses each row into a list containing the book title as the first element and the author as the second:

[
    ["The Devil in the White City", "Erik Larson"],
    ["The Lion, the Witch and the Wardrobe", "C.S. Lewis"],
    ["In the Garden of Beasts", "Erik Larson"]
]

We use the asLists method — supplying a String.class argument — to convert the DataTable argument to a List<List<String>>. This Class argument informs the asLists method what data type we expect each element to be.

In our case, we want the title and author to be String values, so we supply String.class:

@Given("^I have the following books in the store by list$")
public void haveBooksInTheStoreByList(DataTable table) {
    
    List<List<String>> rows = table.asLists(String.class);
    
    for (List<String> columns : rows) {
        store.addBook(new Book(columns.get(0), columns.get(1)));
    }
}

We then iterate over each element of the sub-list and create a corresponding Book object. Lastly, we add each created Book object to our BookStore object.

If we parsed data containing a heading, we would skip the first row since Cucumber does not differentiate between headings and row data for a list of lists.

3.2. List of Maps

While a list of lists provides a foundational mechanism for extracting elements from a data table, the step implementation can be cryptic. Cucumber provides a list of maps mechanism as a more readable alternative.

In this case, we must provide a heading for our table:

Scenario: Correct non-zero number of books found by author by map
  Given I have the following books in the store by map
    | title                                | author      |
    | The Devil in the White City          | Erik Larson |
    | The Lion, the Witch and the Wardrobe | C.S. Lewis  |
    | In the Garden of Beasts              | Erik Larson |
  When I search for books by author Erik Larson
  Then I find 2 books

Similar to the list of lists mechanism, Cucumber creates a list containing each row but instead maps the column heading to each column value.

Cucumber repeats this process for each subsequent row:

[
    {"title": "The Devil in the White City", "author": "Erik Larson"},
    {"title": "The Lion, the Witch and the Wardrobe", "author": "C.S. Lewis"},
    {"title": "In the Garden of Beasts", "author": "Erik Larson"}
]

We use the asMaps method — supplying two String.class arguments — to convert the DataTable argument to a List<Map<String, String>>. The first argument denotes the data type of the key (header) and second indicates the data type of each column value. So, we supply two String.class arguments because our headers (key) and title and author (values) are all Strings.

Then we iterate over each Map object and extract each column value using the column header as the key:

@Given("^I have the following books in the store by map$")
public void haveBooksInTheStoreByMap(DataTable table) {
    
    List<Map<String, String>> rows = table.asMaps(String.class, String.class);
    
    for (Map<String, String> columns : rows) {
        store.addBook(new Book(columns.get("title"), columns.get("author")));
    }
}

3.3. Table Transformer

The final (and most rich) mechanism for converting data tables to usable objects is to create a TableTransformer.

A TableTransformer is an object that instructs Cucumber how to convert a DataTable object to the desired domain object:

 

A transformer converts a DataTable into a desired object

 

Let’s see an example scenario:

Scenario: Correct non-zero number of books found by author with transformer
  Given I have the following books in the store with transformer
    | title                                | author      |
    | The Devil in the White City          | Erik Larson |
    | The Lion, the Witch and the Wardrobe | C.S. Lewis  |
    | In the Garden of Beasts              | Erik Larson |
  When I search for books by author Erik Larson
  Then I find 2 books

While a list of maps, with its keyed column data, is more precise than a list of lists, we still clutter our step definition with conversion logic.

Instead, we should define our step with the desired domain object (in this case, a BookCatalog) as an argument:

@Given("^I have the following books in the store with transformer$")
public void haveBooksInTheStoreByTransformer(BookCatalog catalog) {
    store.addAllBooks(catalog.getBooks());
}

To do this, we must create a custom implementation of the TypeRegistryConfigurer interface.

This implementation must perform two things:

  1. Create a new TableTransformer implementation
  2. Register this new implementation using the configureTypeRegistry method

To capture the DataTable into a useable domain object, we’ll create a BookCatalog class:

public class BookCatalog {
 
    private List<Book> books = new ArrayList<>();
     
    public void addBook(Book book) {
        books.add(book);
    }
 
    // standard getter ...
}

To perform the transformation, let’s implement the TypeRegistryConfigurer interface:

public class BookStoreRegistryConfigurer implements TypeRegistryConfigurer {

    @Override
    public Locale locale() {
        return Locale.ENGLISH;
    }

    @Override
    public void configureTypeRegistry(TypeRegistry typeRegistry) {
        typeRegistry.defineDataTableType(
          new DataTableType(BookCatalog.class, new BookTableTransformer())
        );
    }

   //...

And then we’ll implement the TableTransformer interface for our BookCatalog class:

    private static class BookTableTransformer implements TableTransformer<BookCatalog> {

        @Override
        public BookCatalog transform(DataTable table) throws Throwable {

            BookCatalog catalog = new BookCatalog();
            
            table.cells()
              .stream()
              .skip(1)        // Skip header row
              .map(fields -> new Book(fields.get(0), fields.get(1)))
              .forEach(catalog::addBook);
            
            return catalog;
        }
    }
}

Note that we’re transforming English data from the table, and we therefore return the English locale from our locale() method. When parsing data in a different locale, we must change the return type of the locale() method to the appropriate locale.

Since we included a data table header in our scenario, we must skip the first row when iterating over the table cells (hence the skip(1) call). We would remove the skip(1) call if our table did not include a header.

By default, the glue code associated with a test is assumed to be in the same package as the runner class. Therefore, no additional configuration is needed if we include our BookStoreRegistryConfigurer in the same package as our runner class.

If we add the configurer in a different package, we must explicitly include the package in the @CucumberOptions glue field for the runner class.

4. Handling Empty String With Cucumber Data Table

A common point of confusion when working with Cucumber data tables is how blank cells are processed. Unlike Java, where uninitialized references often default to null, Cucumber consistently interprets empty table cells as literal empty strings (“”). This distinction becomes crucial when our test data includes optional fields.

Building on our bookstore example, we might encounter a scenario like this where author information is occasionally missing:

Scenario: Finding books with some missing author data
  Given I have the following books in the store with transformer
    | title                                | author       |
    | The Devil in the White City          | Erik Larson  |
    | The Lion, the Witch and the Wardrobe | C.S. Lewis   |
    | In the Garden of Beasts              | Erik Larson  |
    | Untitled Manuscript                  |              |  # Empty author cell
    | Anonymous Work                       |              |  # Empty author cell
  When I search for books by unknown authors
  Then I find 2 books

The two books without specified authors don’t receive null values; they’re assigned empty strings. Our transformer needs to account for this:

private static class BookTableTransformer implements TableTransformer<BookCatalog> {
    @Override
    public BookCatalog transform(DataTable table) throws Throwable {
        BookCatalog catalog = new BookCatalog();
        
        table.cells()
          .stream()
          .skip(1)        // Skip header row
          .map(fields -> {
              String title = fields.get(0);
              String author = fields.get(1);
              
              // Handle empty strings
              if (author != null && author.isEmpty()) {
                  author = "Unknown Author"; // Apply default
              }
              
              return new Book(title, author);
          })
          .forEach(catalog::addBook);
        
        return catalog;
    }
}

This pattern extends naturally to other data table approaches. With the maps method, we’d implement similar logic:

@Given("I have these catalog entries")
public void loadCatalogEntries(DataTable table) {
    List<Map<String, String>> entries = table.asMaps(String.class, String.class);
    
    for (Map<String, String> entry : entries) {
        String author= entry.get("author");
        
        if (author != null && author.isEmpty()) {
            author = "Author Unspecified";
        }
        
        inventory.addVolume(new Book(entry.get("title"), author));
    }
}

The fundamental takeaway remains: Cucumber’s data tables populate blank cells with empty strings rather than null references. Our implementation logic must therefore explicitly check for and manage these empty string cases according to our domain requirements.

5. Conclusion

In this article, we looked at how to define a Gherkin scenario with tabular data using a data table.

Additionally, we explored three ways of implementing a step definition that consumes a Cucumber data table.

While a list of lists and a list of maps suffice for basic tables, a table transformer provides a much richer mechanism capable of handling more complex data.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)