Data Table

In the previous chapter we have learned how to iterate scenario with different data. In this chapter we will learn about Data Table. Imagine about a situation where you have to pass lot of different data to a step. For example lets consider registration form. One of the simplest solution is to add each step for one data, but this will end up with too many Given statements. To tackle such situation, Specflow provides Data Table.


A Data Table allows you to pass structured data (like a table) in your feature files to make your scenarios more flexible and detailed.

  • It's a way to organize and pass tabular or structured data directly in your Gherkin feature files.
  • It's particularly handy when you need to provide or verify multiple pieces of related data for a step.
  • They are represented between lines with three or more vertical bars |. Each row in the table is separated by a new line, and cells within a row are separated by pipes |.
  • You can use a data table to pass multiple inputs to a step.

Lets understand this by a new example. Following example contains a scenario of user registration form. Let's name this as registration.feature


Gherkin
Copy
Feature: User registration
  Scenario: Successful User registration
    Given the following user details
    | Name   | Age  | City      |
    | John  | 25   | New York  |
    When the user submits the registration form
    Then the user should be registered successfully


In the above feature file, under the Given step we have a data table which supplies the complete data table to that step. Here it wont be iterated, rather it will be passed as whole.

Now let's see the step definition file. In the following step definition file, we have used Table object to retrieve the data from the feature file.

Java
Copy
using TechTalk.SpecFlow;
using Xunit;

[Binding]
public class UserDetails
{

	Given("the following user details")]
	public void enterUserDetails(Table table) 
	{
		foreach (var row in table.Rows)
			{
				String name = row["Name"];
				String age = row["Age"];
				String city = row["City"];
				// Perform any necessary operations with the numbers
			}

	}
	[When("the user submits the registration form")]
	public void theUserSubmitsTheRegistrationForm() 
	{
		Console.WriteLine("User submits the registration form");
	}

	[Then("the user should be registered successfully")]
	public void theUserShouldBeRegisteredSuccessfully() 
	{
		Console.WriteLine("User registered successfully");
	}

}
In the above step definitions, you'll receive the data table as a structured object (in this case, DataTable), allowing you to process or utilize the data within your test steps.