如何配置SpecFlow实现Table到IEnumerable<T>的自动参数转换?
SpecFlow全局自动转换Table到IEnumerable
我现在有大量重复代码,比如每个步骤方法都要手动把Table转成对应类型的集合:
[Given(@"user amortizes the deductions:")] public void GivenUserAmortizesTheDeductions(Table table) { var tableRows = table.CreateSet<MyTableRow>(); }
后来尝试用[StepArgumentTransformation]来做转换,但还是要为每个新的行类型写重复的转换方法:
[StepArgumentTransformation] public static IEnumerable<FooRow> FooTable(Table table) { return table.CreateSet<FooRow>(); } [StepArgumentTransformation] public static IEnumerable<BarRow> BarTable(Table table) { return table.CreateSet<BarRow>(); }
问题:能不能配置SpecFlow,让它自动把Table转换成IEnumerable<T>,不用每次都显式定义转换关系?
解决方案:使用泛型的全局步骤参数转换
只需要定义一个泛型的StepArgumentTransformation方法,就能一次性支持所有符合条件的IEnumerable<T>类型转换,无需重复写转换逻辑:
[StepArgumentTransformation] public static IEnumerable<T> TransformTableToEnumerable<T>(Table table) where T : class, new() { return table.CreateSet<T>(); }
使用方式
之后你的步骤方法可以直接声明接收IEnumerable<T>类型的参数,SpecFlow会自动完成Table到目标集合的转换:
[Given(@"user amortizes the deductions:")] public void GivenUserAmortizesTheDeductions(IEnumerable<MyTableRow> tableRows) { // 直接使用tableRows即可,无需手动调用CreateSet } [When(@"user adds the following items:")] public void WhenUserAddsTheFollowingItems(IEnumerable<FooRow> items) { // 直接使用items }
注意事项
- 你的行类型(比如
MyTableRow、FooRow)必须是类,并且拥有无参构造函数,因为table.CreateSet<T>方法依赖这两个条件才能正常创建对象并填充属性。
内容的提问来源于stack exchange,提问作者THX-1138
相关产品推荐
相关产品推荐

