如何将Spec-flow表数据转换为不同的值

我需要转换通过table.CreateInstance()table.CreateSet()获得的Spec-flow表数据。 我正在使用Spec流进行数据库测试,在某些情况下,Table字段值需要映射到不同的值,因为DB表存储代码而不是我们在function文件表中输入的值。 我不想在function文件中包含代码,因为它会降低可读性。 例如,如果我已经输入Single for status,如下所述,我希望它在数据传输对象/ POCO中映射或转换为S. 什么是最好的方法? 提前致谢。

 Given I entered the following data into the new account form: | Name | Birthdate | Status | | John Butcher| 2/2/1902 | Single | 

我不知道自动这样做,所以我只能想到两种可能性。

  1. 不要使用CreateInstanceCreateSet方法,而是手动执行所有映射,但将其封装在[StepArgumentTransformation]
  2. 使用您正在使用的方法,然后在创建实例后用“S”覆盖自动生成的“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(); var account = form.CreateInstance(); // save to the database } 

对于这个特定的例子,它可能比你需要的更多,但是我发现当场景中的数据需要采用人类可读的格式时,这种模式很有效,后者在你的域模型中被转换为复杂的格式。

正如Sam指出的那样,我们可以使用StepArgumentTransformarion或类似于下面的方法。 如果要将Value1映射到一个类型的Code1而将Value1映射到另一个类型的Code1,并使用typeof(T).Name.Equals(typeof(yourtype).Name)作为条件,则在扩展方法中添加if else

  public static IEnumerable CreateSetWithValueTransfer(this Table table) { var mapper = new Dictionary(StringComparer.InvariantCultureIgnoreCase) { {"Value1", "Code1"}, {"value2", "Code2"} }; var set = ChangeValues(table, mapper); return set.CreateSet(); } private static Table ChangeValues(Table table, Dictionary 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相对容易地完成它。