我需要转换通过table.CreateInstance()
或table.CreateSet()
获得的Spec-flow表数据。我正在使用Spec flow进行数据库测试,在某些情况下,表字段值需要映射为不同的值,因为数据库表存储代码,而不是我们在功能文件表中输入的值。我不想在功能文件中包含代码,因为它会降低可读性。例如,如果我为如下所述的状态输入了Single,我希望在数据传输对象/ POCO中将其映射或转换为S。最好的方法是什么?预先感谢。
Given I entered the following data into the new account form:
| Name | Birthdate | Status |
| John Butcher| 2/2/1902 | Single |
我已经开始使用“测试模型”,最终成为我的规格流程测试的视图模型。
使用您的示例:
Given I entered the following data into the new account form:
| Name | Birthdate | Status |
| John Butcher| 2/2/1902 | Single |
域模型:
public class Account
{
public string Name { get; set; }
public DateTime? Birthdate { get; set; }
public string Status { get; set; }
}
和“测试模型”:
public class AccountForm
{
public string Name { get; set; }
public DateTime? Birthdate { get; set; }
public string Status { get; set; }
public Account CreateInstance()
{
return new Account()
{
Name = Name,
Birthdate = Birthdate,
Status = Status.Substring(0, 1)
};
}
}
步骤定义:
[Given(@"Given I entered the following data into the new account form:")]
public void GivenIEnteredTheFollowingDataIntoTheNewAccountForm(Table table)
{
var form = table.CreateInstance<AccountForm>();
var account = form.CreateInstance();
// save to the database
}
对于这个特定示例,它可能超出了您的需要,但是我发现,当场景中的数据需要采用人类可读的格式时,这种模式就可以很好地工作,并且可以在域模型中将其转换为复杂的格式。 。
我仍然不知道自动执行此操作,因此我只能想到两种可能性。
CreateInstance
或CreateSet
方法,而是手动完成所有映射,而是将其封装在[StepArgumentTransformation]
中正如Sam指出的,我们可以使用StepArgumentTransformarion或类似下面的方法。如果要使用[StepArgumentTransformation]
作为条件将一种类型的Value1映射到Code1并将另一种类型的Value1映射到CodeX,则在扩展方法内添加if,
typeof(T).Name.Equals(typeof(yourtype).Name)
我用 public static IEnumerable<T> CreateSetWithValueTransfer<T>(this Table table)
{
var mapper = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)
{
{"Value1", "Code1"},
{"value2", "Code2"}
};
var set = ChangeValues(table, mapper);
return set.CreateSet<T>();
}
private static Table ChangeValues(Table table, Dictionary<string, string> mapper)
{
var mappedTable = new Table(table.Header.ToArray());
foreach (var row in table.Rows)
{
mappedTable.AddRow(row.Values.Select(x => mapper.ContainsKey(x) ? mapper[x] : x).ToArray());
}
return mappedTable;
}
提出了类似的问题。似乎应该可以将StepArgumentTransforms应用于CreateInstance / CreateSet,但对于尚未在表转换中进行转换的基本类型,尚未实现。
您可以通过]从表中获取值>
ValueRetriever