2013-01-16 59 views
0

所以,我用MVC應用程序,我的團隊使用SpecFlow測試工作,以驗證器的屬性。我使用here描述的[RequiredIf(prop, val)]的實現。約束力的SpecFlow單元測試

但是,我發現了一個「輕微」的問題 - 而驗證工作只是正常的網頁,他們在我們的單元測試突破!經過調查,我發現該屬性的IsValid()方法在我們的單元測試中被直接調用......可能是因爲該屬性未綁定到Validator。

在那個博客,我也跟着安裝步驟,註冊驗證程序RequiredIf屬性。但是,爲了某些單元測試的目的,我需要找出在測試設置中綁定驗證的位置。

我已經嘗試了一些更多或更少的邏輯選擇:

[Binding] 
public class TestSteps 
{ 
    // Every test has to call this helper to load up the controller... 
    private void GoToHome() 
    { 
     // SNIP: Unimportant 
     DataAnnotationsViewModelValidatorProvider.RegisterAdapter(..., ...); 
    } 
} 

...以及在測試套件文件...

// See attribute for why I figured this may be a logical choice. 
[BeforeScenario] 
public void Setup() 
{ 
    DataAnnotationsViewModelValidatorProvider.RegisterAdapter(..., ...); 
} 

...然而,出於某種原因,無論是位置導致RequiredIf()綁定到其RequiredIfValidator()

問題:對於單元測試,我應該在哪裏放置屬性 - >驗證器綁定,這樣我的單元測試將正確驗證裝飾的屬性,如果RequiredIf()

回答

0

我不得不承認,我不熟悉的MVC驗證所以這可能會或可能無法正常工作。

不過,我猜想,如果你單獨使用NUnit,你可能想要做這樣的事情

[FixtureSetup] 
public void ....() 
{ 
    DataAnnotationsViewModelValidatorProvider.RegisterAdapter(..., ...); 
} 

而此刻的你實際上是通過綁定,這是一個整體加入您的驗證反射一跳。

但是,如果你在自動生成的xxxxx.feature.cs看文件,你可以看到類實際上定義爲

[System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.8.1.0")] 
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 
[NUnit.Framework.TestFixtureAttribute()] 
[NUnit.Framework.DescriptionAttribute("xxxxx")] 
public partial class xxxxxFeature 
{ 

顯然,我們不能編輯這一點,但我們可以創建另一個文件在部分類中實現我們喜歡的任何東西。

在xxxxx.partial.cs

public partial class xxxxxFeature 
{ 
    [FeatureSetup] 
    .... 

如果不出意外,你有幾個地方試試。祝你好運。

+0

感謝您的建議!現在,我決定爲我的'RequiredIf.IsValid()'實現增加更多的責任,不再需要註冊。感謝您考慮答案 - 即使我們不能拿出一個:( –