温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - How to transform Spec-flow table data into different values
c# cucumber bdd specflow

c# - 如何将规格流表数据转换为不同的值

发布于 2020-04-15 00:18:36

我需要转换通过table.CreateInstance()获取的Spec-flow表数据table.CreateSet()我正在使用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      |

查看更多

提问者
Rasika
被浏览
25
2016-08-16 22:31

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

 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;
    }