Reputation: 1977
I am trying to do some intial setup which sets up the environment for the scenarios under a particular feature. I clubbed the setup data in a separate class. I added a specflow hook file and modified it to serve as before feature hook. Then I tried using Context Injection. In the I created a private variable of the setup class and a constructor (taking an object of the setup class) for the BeforeScenario hook file.
The issue I am facing is that the BeforeFeature method has to static as per specflow. And if I make my private setup class static, then the constructor is not getting called.
Is what I am doing right? Or Is it even possible what I am trying to do?
[Binding]
public class BeforeFeature
{
private static SetUp setUp;
public BeforeFeature(SetUp setUpObject)
{
setUp = setUpObject;
}
[BeforeFeature]
public static void RunBeforeFeature()
{
//Some processing.
setUp.baseDir = "some data";
setUp.status = "some data"
}
}
Upvotes: 2
Views: 4237
Reputation: 32936
You can tell SpecFlows context injection framework that you have an object it should use when a Step class asks for an instance in its constructor. This can be done like shown in the example:
[Binding]
public class BeforeFeature
{
private readonly IObjectContainer objectContainer;
private static SetUp setUp;
public BeforeFeature(IObjectContainer container)
{
this.objectContainer = objectContainer;
}
[BeforeFeature]
public static void RunBeforeFeature()
{
//Some processing.
setUp.baseDir = "some data";
setUp.status = "some data"
}
[BeforeScenario]
public void RunBeforeScenario()
{
objectContainer.RegisterInstanceAs<SetUp>(setUp);
}
}
You do the setup before the Scenario not the feature but if you only create the SetUp
once and set its values in the [BeforeFeature]
then you should get the same instance in each scenario so any modifications made there should stick (assuming this is what you want, otherwise just create a new SetUp
in the BeforeScenario
method)
As long as your Step classes now ask for a SetUp
instance in the constructor they should get the one you placed in the container.
Upvotes: 8