是的,您可以創建全球的BeforeScenario和AfterScenario方法,但實際上我發現這是不可取的,因爲通常在步驟之前和之後步驟不適用於所有步驟的測試項目。
相反,我創建一個基類爲我的步驟定義,這將對我想例如適用於所有的我的情景BeforeScenario和AfterScenarios方法
public class BaseStepDefinitions
{
[BeforeScenario]
public void BeforeScenario()
{
// BeforeScenario code
}
[AfterScenario]
public void AfterScenario()
{
// AfterScenario code
}
}
請注意,我沒有使用這個類的Binding屬性。如果您確實包含它,那麼BeforeScenario和AfterScenario步驟將是全球性的。
然後我得到這個基地步驟定義類我一步definion班,使他們有前和情景方法如後
[Binding]
public class SpecFlowFeature1Steps : BaseStepDefinitions
{
[Given(@"I have entered (.*) into the calculator")]
public void GivenIHaveEnteredIntoTheCalculator(int inputValue)
{
ScenarioContext.Current.Pending();
}
[When(@"I press add")]
public void WhenIPressAdd()
{
ScenarioContext.Current.Pending();
}
[Then(@"the result should be (.*) on the screen")]
public void ThenTheResultShouldBeOnTheScreen(int expectedResult)
{
ScenarioContext.Current.Pending();
}
}
雖然這種方法不是全局,使所有的StepDefinitions從BaseStepDefinition類派生我們實現相同的效果。
它也提供了更多的控制,即如果你不希望BeforeScenario或AfterScenario結合那麼不從基礎步驟得到根本。
對不起,這不起作用。一旦你開始使用多個綁定類,你最終會有多個調用。例如,如果我延長上面的例子綁定分成三類,
[Binding]
public class SpecFlowFeature1Steps : BaseStepDefinitions
{
[Given(@"I have entered (.*) into the calculator")]
public void GivenIHaveEnteredIntoTheCalculator(int inputValue)
{
//ScenarioContext.Current.Pending();
}
}
[Binding]
public class SpecFlowFeature2Steps : BaseStepDefinitions
{
[When(@"I press add")]
public void WhenIPressAdd()
{
//ScenarioContext.Current.Pending();
}
}
[Binding]
public class SpecFlowFeature3Steps : BaseStepDefinitions
{
[Then(@"the result should be (.*) on the screen")]
public void ThenTheResultShouldBeOnTheScreen(int expectedResult)
{
//ScenarioContext.Current.Pending();
}
}
public class BaseStepDefinitions
{
[BeforeScenario]
public void BeforeScenario()
{
// BeforeScenario code
Console.WriteLine("Before. [Called from "+ this.GetType().Name+"]");
}
[AfterScenario]
public void AfterScenario()
{
// AfterScenario code
Console.WriteLine("After. [Called from " + this.GetType().Name + "]");
}
}
然後當我運行它時,輸出爲
Before. [Called from SpecFlowFeature1Steps]
Before. [Called from SpecFlowFeature2Steps]
Before. [Called from SpecFlowFeature3Steps]
Given I have entered 50 into the calculator
-> done: SpecFlowFeature1Steps.GivenIHaveEnteredIntoTheCalculator(50) (0.0s)
And I have entered 70 into the calculator
-> done: SpecFlowFeature1Steps.GivenIHaveEnteredIntoTheCalculator(70) (0.0s)
When I press add
-> done: SpecFlowFeature2Steps.WhenIPressAdd() (0.0s)
Then the result should be 120 on the screen
-> done: SpecFlowFeature3Steps.ThenTheResultShouldBeOnTheScreen(120) (0.0s)
After. [Called from SpecFlowFeature1Steps]
After. [Called from SpecFlowFeature2Steps]
After. [Called from SpecFlowFeature3Steps]
AlSki和Truan是正確的,這個答案沒有按預期工作。不接受並接受Alkski的,我會刪除我的答案。 –