Specflow table 列绑定防止空值

Specflow table column binding prevent Nulls

给定以下代码:

public class Bob {
   public string Name { get; set; }
   public int Age { get; set; }
   public decimal Height { get; set; }
}

Feature: Bob checker

Scenario: Check Bob
  Given I have the following Bob
     | Name   | Age | Hieght |
     | Robert | 63  | 1.87   |
  When . . . . 
  Then . . . . 

[Given(@"I have the following Bob")]
public void IHaveTheFollowingBob(Table table) {
    var bob = table.CreateInstance<Bob>();
}

您注意到单词 'Height' 在 table 中的拼写不正确。 CreateInstance 方法仍然有效,但 Bob 对象上的 'Height' 将为 0 或引用类型为 null。

如果列未绑定到提供的类型,是否有办法使 SpecFlow 失败。谢谢

如果有列与任何 class 属性都不匹配,则不会抛出错误。

但是有一个变通办法。您可以实现一种方法来检查是否有 "invalid" 列以防止拼写错误:

    [Given("I have the following Bob")]
    public void TestMethod1(Table table)
    {
        AssertAllTableColumnsMatch<Bob>(table);

        var bob = table.CreateInstance<Bob>();
    }

    public void AssertAllTableColumnsMatch<T>(Table table)
    {
        foreach (var header in table.Header)
        {
            bool columnHeaderMatches = HasProperty(typeof(T), header);

            Assert.IsTrue(columnHeaderMatches,
                string.Format("The column header [{0}] does not match any property of the type [{1}]",
                header, typeof(T).Name));
        }
    }

    private bool HasProperty(Type obj, string propertyName)
    {
        return obj.GetProperty(propertyName) != null;
    }

会抛出以下错误: -> error: Assert.IsTrue failed. The column header [Hieght] does not match any property of the type [Bob]

该方法简单地迭代所有列并检查提供的类型是否具有这样的 属性。

我应该RTFM。如果 属性 不存在或未正确填充,table.CompareToInstance(bob); 将失败。如果您将它与 table.CreateInstance 结合使用,您将在有空值的地方遇到失败。在这里留下问答,以防万一其他人脑残。

SpecFlow Assist Helper, CompareToInstance

如果您有复杂类型,您可以在 table 中表示它们并使用 IValueRetrieverIValueComparer extensions

例如考虑以下米奇老鼠代码:

public class Bob {
   public string Name { get; set; }
   public int Age { get; set; }
   public decimal Height { get; set; }
}

public class BobModel {
   public string Name { get; set; }
   public int Age { get; set; }
   public decimal Height { get; set; }
}

Feature: Bob checker

Scenario: Check Bob
  Given I have the following Bob
     | Name   | Age | Hieght |
     | Robert | 63  | 1.87   |
  When I map this to the model
  Then Bob the model looks like this
     | Name   | Age | Height |
     | Robert | 63  | 1.87   |

[Given(@"I have the following Bob")]
public void IHaveTheFollowingBob(Table table) {
    var bob = table.CreateInstance<Bob>();
}

[When(@"I map this to the model")]
public void IMapThisToTheModel() {
   sut = production.Map(bob);
}

[Then(@"Bob the model looks like this") {
public void BobTheModelLooksLikeThis(Table table) {
   table.CompareToInstance<BobModel>(sut);
}

在这种情况下,如果第二个 table 中有拼写错误,它会失败并提示找不到 属性。如果第一个 table 中有拼写错误,那么它仍然为空,但断言将失败。无误报