あなたはTechTalk.SpecFlow.Tableクラスの拡張メソッドとしてこれを実装して使用する事が容易にするためにC#で少しクラスの反射を利用することができる:
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));
}
}
}
これはあなたのマッチングとDataTable
を与えます列名、およびオーバーロードが存在し、強い型付けされた列を持つDataRow
オブジェクトが作成されます。
Given Num List
| num |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
そして、ステップ定義:あなたたとえば
、あなたはとしてそれを使用することになり
[Given(@"...")]
public void GivenNumList(Table table)
{
DataTable dataTable = table.ToDataTable<int>();
// dataTable.Rows[0]["num"] is an int
}
あなたはToDataTable
のオーバーロードを追加し続けると、プロジェクトのニーズ限り多くのジェネリック型を指定することができますそのロジックは素晴らしく汎用的であり、非常に再利用可能です。
次の2つの列を持つSpecFlowテーブルを持っていた場合:
Given some list
| age | name |
| 2 | Billy |
| 85 | Mildred |
ステップの定義は次のようになります。
public void GivenSomeList(Table table)
{
DataTable dataTable = table.ToDateTable<int, string>();
// use it
}
あなたはSpecFlow列を指定するために、ジェネリック型を指定します。
このコードはお役に立ちます。ありがとう –