我需要在小 cucumber 中实现数据表。但是他们只允许表格而不是数据表。我如何在 Gherkin 中实现数据表?
我试过: 这是我的小 cucumber 语法
Scenario: Select Even Numbers From The list
Given Num List
| num |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
Then the result should even numbers only on the screen.
这是生成步骤定义后的代码。这里的函数参数是Table。(如何可能Data table而不是table?)。
public void GivenNumList(Table table)
{
}
最佳答案
您可以将其作为 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
的重载,并根据您的项目需要指定尽可能多的泛型类型,并且逻辑很好且通用,使其非常可重用。
如果您有一个包含两列的 SpecFlow 表:
Given some list
| age | name |
| 2 | Billy |
| 85 | Mildred |
步骤定义为:
public void GivenSomeList(Table table)
{
DataTable dataTable = table.ToDateTable<int, string>();
// use it
}
按照指定 SpecFlow 列的顺序指定通用类型。
关于c# - 如何在gherkin中实现techtalk.specflow中的数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44016458/