Specflow 中的多行和多列

Multiple lines and columns in Specflow

我有一个 Specflow table 看起来像这样。

 When I Perform POST Operation for "/example/" with body
 | answerValue1  | answerValue2 | countryCode | Cash    |
 | Yes           | Yes          | AD          | 76-100% |  
 |               |              | AF          |         |

CountryCode这一列是唯一可以多选的。 我试图做的是使用简单的 tableExtensions

将列添加到字典中
 public class TableExtensions
        {
            public static Dictionary<string, string> ToDictionary(Table table)
            {
                var dictionary = new Dictionary<string, string>();
                foreach (var row in table.Rows)
                {
                    dictionary.Add(row[0], row[1]);
                }
                return dictionary;
            }
      }

并从方法中调用它。

var dictionary = TableExtensions.ToDictionary(table);
var countryCode = dictionary["countryCode"];

不幸的是,我收到错误 字典中不存在给定的键, 因为字典只有 returns 来自第一个和第二个键的两个值

当然,如果我将键更改为 row[2], row[3],它会得到正确的列。 但我想重用 Table 扩展。

我也尝试增加它们,但只用了第一个列

 var i = 0;
                foreach (var row in table.Rows)
                {
                    dictionary.Add(row[i], row[i]);
                    i++;
                }

有没有人有更好的解决方案?

我不完全确定你希望字典最终包含什么,但正如你提到的,手动将它查找的行更改为:

row[2], row[3]

提供您想要的数据,也许这会为您提供您正在寻找的可重用性:

 public class TableExtensions
    {
        public static Dictionary<string, string> ToDictionary(Table table, int columnOne, int columnTwo)
        {
            int i = 0;

            var dictionary = new Dictionary<string, string>();
            foreach (var row in table.Rows)
            {
                dictionary.Add(row[columnOne], row[columnTwo]);
            }
            return dictionary;
        }
    }

用法:

var dictionary = TableExtensions.ToDictionary(table, 2, 3);

这会生成一个包含以下内容的字典:

您可以获得这样的国家代码:

foreach (var row in dictionary)
{
    var countryCode = row.Key;
    var score = row.Value ?? string.empty;
}  

鉴于国家/地区代码的简单性,我会将它们设为逗号分隔列表并使用垂直 table 代替:

When I Perform POST Operation for "/example/"
    | Field        | Value  |
    | answerValue1 | ...    |
    | answerValue2 | ...    |
    | countryCodes | AD, AF |
    | cash         | ...    |

在您的步骤定义中:

var example = table.CreateInstance<ExampleRow>();

// use example.GetCountryCodes();

和 ExampleRow class 将 table 解析为一个对象:

public class ExampleRow
{
    public string AnswerValue1 { get; set; }
    public string AnswerValue2 { get; set; }

    private string[] countryCodes;

    public string CountryCodes
    {
        get => string.Join(", ", countryCodes);
        set => countryCodes = value.Split(", ");
    }

    public string[] GetCountryCodes()
    {
        return countryCodes;
    }
}