使用NUnit的Specflow不尊重TestFixtureSetUpAttribute

mue*_*uek 5 structuremap nunit specflow

我正在使用SpecFlow和Nunit,我正在尝试使用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()
    {
    }
Run Code Online (Sandbox Code Playgroud)

解:

[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()
    {
    }
Run Code Online (Sandbox Code Playgroud)

nem*_*esv 6

TestInitialize没有被调用,因为它在你的Steps类中,而不在单元测试中(因为实际的单元测试在.cs你的.feature文件中生成).

SpecFlow有自己的测试生命周期事件,称为钩子,这些都是预定义的挂钩:

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

请注意,这可以提高设置的灵活性.有关其他信息,请参阅文档.

根据您要使用该TestFixtureSetUp属性的事实,您可能需要BeforeFeature在每个功能之前调用一次的钩子,因此您需要编写:

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

        throw new Exception("BBB");
    }

    //...
}
Run Code Online (Sandbox Code Playgroud)

请注意,该[BeforeFeature]属性需要一个static方法.

您还应该注意,如果您正在使用VS集成,则会调用一个项目项类型SpecFlow Hooks (event bindings),该类型会创建一个带有一些预定义挂钩的绑定类,以帮助您入门.