2017-06-23 85 views
0

考慮下面的代碼:Specflow表列綁定防止空值

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

You'l注意單詞「身高」沒有在表中拼寫正確。 CreateInstance方法仍然可以工作,但Bob對象上的「高度」將爲0或引用類型爲null。

如果列未綁定到所提供的類型,是否有方法使SpecFlow失敗?謝謝

回答

1

有沒有這樣的事情,如果有一列不匹配任何類屬性拋出錯誤。

然而,有一個工作的週末。你可以實現一個方法來檢查,如果有一個「無效」一欄,以防止錯別字:

[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]

這個方法簡單地遍歷所有列,如果檢查提供的類型具有這種屬性。

0

我應該RTFM。 table.CompareToInstance(bob);如果該屬性不存在或沒有正確填充,將會失敗。如果你使用這個結合table.CreateInstance你會得到失敗的地方有空值。離開Q &這裏只是爲了防止任何人腦部失敗。

SpecFlow Assist Helper, CompareToInstance

如果你有複雜的類型,你可以代表他們在表和使用IValueRetrieverIValueComparerextensions

例如,考慮下面的米老鼠代碼:

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

在這例如,如果第二個表中有拼寫錯誤,它將失敗,說它找不到該屬性。如果第一個表中有拼寫錯誤,那麼這仍然是空的,但斷言將失敗。沒有誤報

+0

如何使用CompareToInstance(..),因爲您沒有您嘗試在步驟中創建的實例?如果你拋出一個虛擬實例,比較會拋出一個異常。 – valentinvs

+0

@valentinvs只是編輯答案更完整。 – jolySoft