In the previous chapter of Transform Table into Dictionarywe provided Vertical Data using Tables. That is useful when we have a long list of Data for e.g. Personal Information includes First Name, Last Name, Address and Job etc.

But this has some limitations like what if we want to execute the same step more than one time, it is not easy to manage that with Dictionary Key Value pair. To obtain the functionality, it is required to use Horizontal Data rather than Vertical Data and that can be done by “Transform Table into DataTable“.

Transform Table into DataTable

We will be using the same example of LogIn Feature and modify it according to our usage. Before moving on to this chapter, please have a look at the base chapter of Data Driven Testing and see how the simple functionality works for LogIn Scenario.

1) Create a New Step

The first step is to create a new Step which will take Data in Table format. It is again an easy job to specify data for the step in Horizontalformat. Just provide the Headerand their values.

1

2

3

When User enter credentials

|Username|Password|

|testuser_1|Test@123|

2) Create a New Step Definition

The second step is to create a new Steps Definition for newly created step, which can be done if bring the cursor on the created step and press F12. The Specflow will display the pop up with Skeleton body of the step, which can be copied and used accordingly.

1

2

3

4

5

[When(@"User enter credentials")]

publicvoidWhenUserEnterCredentials(Table table)

{

}

3) Transform table in to DataTable

To convert Tablein to DataTable, it is required to use System.Data package (using System.Data).

Create a new folder in the solution and name it as Utils. Then create a new C# class with the name TableExtensionsin the same folder and create a new static method called ToDataTable(), which will accept Table data.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

publicstaticDataTable ToDataTable(Table table)

{

vardataTable=newDataTable();

foreach(varheader intable.Header)

{

dataTable.Columns.Add(header,typeof(string));

}

foreach(varrow intable.Rows)

{

varnewRow=dataTable.NewRow();

foreach(varheader intable.Header)

{

newRow.SetField(header,row[header]);

}

dataTable.Rows.Add(newRow);

}

returndataTable;

}

4) Complete Step Definition Method

Now make a use of ToDataTable function and convert the Table data into DataTable.