我正在使用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()
{
}
解决方案:
[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()
{
}
答案 0 :(得分:6)
您的TestInitialize
未被调用,因为它位于您的Steps类中,而不是在单元测试中(因为实际的单元测试位于.cs
内,而.feature
是从[BeforeTestRun]
生成的文件)。
SpecFlow拥有自己的测试生命周期事件,称为钩子,这些都是预定义的钩子:
[AfterTestRun]
/ [BeforeFeature]
[AfterFeature]
/ [BeforeScenario]
[AfterScenario]
/ [BeforeScenarioBlock]
[AfterScenarioBlock]
/ [BeforeStep]
[AfterStep]
/ TestFixtureSetUp
请注意,这样可以提高设置的灵活性。有关其他信息see the documentation。
基于您要使用BeforeFeature
属性的事实,您可能需要[Binding]
public class UsersCRUDSteps
{
[BeforeFeature]
public static void TestInitialize()
{
ObjectFactory.Initialize(x =>
{
x.For<IDateTimeService>().Use<DateTimeService>();
});
throw new Exception("BBB");
}
//...
}
挂钩,在每个功能之前将调用一次,因此您需要编写:
[BeforeFeature]
请注意,static
属性需要SpecFlow Hooks (event bindings)
方法。
您还应该注意,如果您正在使用VS集成,则会有一个名为{{1}}的项目项类型,它会创建一个带有一些预定义挂钩的绑定类,以帮助您入门。