2012-11-01 34 views
5

我正在使用SpecFlow與Nunit,我試圖設置我的環境測試使用TestFixtureSetUpAttribute,但它從來沒有被調用。與NUnit Specflow不尊重TestFixtureSetUpAttribute

我已經嘗試使用MSTests和ClassInitialize屬性,但同樣的情況發生。該函數未被調用。

任何想法爲什麼?

[Binding] 
public class UsersCRUDSteps 
{ 
    [NUnit.Framework.TestFixtureSetUpAttribute()] 
    public virtual void TestInitialize() 
    { 
     // THIS FUNCTION IS NEVER CALLER 

     ObjectFactory.Initialize(x => 
     { 
      x.For<IDateTimeService>().Use<DateTimeService>(); 
     }); 

     throw new Exception("BBB"); 
    } 

    private string username, password; 

    [Given(@"I have entered username ""(.*)"" and password ""(.*)""")] 
    public void GivenIHaveEnteredUsernameAndPassword(string username, string password) 
    { 
     this.username = username; 
     this.password = password; 
    } 

    [When(@"I press register")] 
    public void WhenIPressRegister() 
    { 
    } 

    [Then(@"the result should be default account created")] 
    public void ThenTheResultShouldBeDefaultAccountCreated() 
    { 
    } 

解決方案:

[Binding] 
public class UsersCRUDSteps 
{ 
    [BeforeFeature] 
    public static void TestInitialize() 
    { 
     // THIS FUNCTION IS NEVER CALLER 

     ObjectFactory.Initialize(x => 
     { 
      x.For<IDateTimeService>().Use<DateTimeService>(); 
     }); 

     throw new Exception("BBB"); 
    } 

    private string username, password; 

    [Given(@"I have entered username ""(.*)"" and password ""(.*)""")] 
    public void GivenIHaveEnteredUsernameAndPassword(string username, string password) 
    { 
     this.username = username; 
     this.password = password; 
    } 

    [When(@"I press register")] 
    public void WhenIPressRegister() 
    { 
    } 

    [Then(@"the result should be default account created")] 
    public void ThenTheResultShouldBeDefaultAccountCreated() 
    { 
    } 

回答

6

TestInitialize不叫,因爲它是你的腳步類中,而不是裏面的單元測試(因爲實際的單元測試是從產生.cs裏面你.feature文件)。

SpecFlow都有它被稱爲鉤自己的測試千載難逢的事件,這些都是預定義的掛鉤:

  • [BeforeTestRun]/[AfterTestRun]
  • [BeforeFeature]/[AfterFeature]
  • [BeforeScenario]/[AfterScenario]
  • [BeforeScenarioBlock]/[AfterScenarioBlock]
  • [BeforeStep]/[AfterStep]

請注意,這可以提高設置的靈活性。有關其他信息see the documentation

根據您要使用的TestFixtureSetUp屬性,你可能會需要BeforeFeature鉤將一次每個功能之前被調用的事實,所以你需要寫:

[Binding] 
public class UsersCRUDSteps 
{ 
    [BeforeFeature] 
    public static void TestInitialize() 
    {    
     ObjectFactory.Initialize(x => 
     { 
      x.For<IDateTimeService>().Use<DateTimeService>(); 
     }); 

     throw new Exception("BBB"); 
    } 

    //... 
} 

注意,[BeforeFeature]屬性需要一個static方法。

您還應該注意,如果您使用的是VS集成,則會有一個名爲SpecFlow Hooks (event bindings)的項目項類型,它創建一個具有一些預定義掛鉤的綁定類以幫助您開始。

+1

謝謝,它的工作。我只需要將我的功能更改爲靜態 – muek