Sie könnten dies als eine Erweiterung Methode, um die TechTalk.SpecFlow.Table Klasse implementieren und eine kleine Klasse Reflexion in C# verwenden, um die Dinge einfach zu machen verwenden:
namespace YourTestProject
{
public static class SpecFlowTableExtensions
{
public static DataTable ToDataTable(this Table table, params Type[] columnTypes)
{
DataTable dataTable = new DataTable();
TableRow headerRow = table.Rows[0];
int headerCellCount = headerRow.Count();
for (int i = 0; i < headerCellCount; i++)
{
string columnName = headerRow[i];
Type columnType = columnTypes[i];
dataTable.Columns.Add(columnName, columnType);
}
foreach (var row in table.Rows.Skip(1))
{
var dataRow = dataTable.NewRow();
for (int i = 0; i < headerCellCount; i++)
{
string columnName = headerRow[i];
Type columnType = columnTypes[i];
dataRow[columnName] = Convert.ChangeType(row[i], columnType);
}
dataTable.AddRow(dataRow);
}
return dataTable;
}
public static DataTable ToDataTable(this Table table)
{
return table.ToDataTable<string>();
}
public static DataTable ToDataTable<TColumn0>(this Table table)
{
return table.ToDateTable(typeof(TColumn0));
}
public static DataTable ToDataTable<TColumn0, TColumn1>(this Table table)
{
return table.ToDateTable(typeof(TColumn0), typeof(TColumn1));
}
public static DataTable ToDataTable<TColumn0, TColumn1, TColumn2>(this Table table)
{
return table.ToDateTable(typeof(TColumn0), typeof(TColumn1), typeof(TColumn2));
}
}
}
Dies wird Ihnen ein DataTable
geben mit passendem Spaltennamen und Überladungen existieren, um DataRow
Objekte mit stark typisierten Spalten zu erstellen.
Für Ihr Beispiel würden Sie es als verwenden:
Given Num List
| num |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
Und der Schrittdefinition:
[Given(@"...")]
public void GivenNumList(Table table)
{
DataTable dataTable = table.ToDataTable<int>();
// dataTable.Rows[0]["num"] is an int
}
Sie halten könnten Überlastungen von ToDataTable
und geben so viele generische Typen wie Ihre Projektanforderungen Hinzufügen und die Logik ist nett und generisch, wodurch sie sehr wiederverwendbar ist.
Wenn Sie eine SpecFlow Tabelle mit zwei Spalten haben:
Given some list
| age | name |
| 2 | Billy |
| 85 | Mildred |
Der Schritt Definition wäre:
public void GivenSomeList(Table table)
{
DataTable dataTable = table.ToDateTable<int, string>();
// use it
}
die generischen Typen in der Reihenfolge Geben Sie die SpecFlow Spalten angeben.
Dieser Code ist hilfreich, Danke –