NUnit Specflow how to share a class instance for all tests

There are a few ways to do this. Most are covered on this page

What I personally would probably do is define a SeleniumContext class and require this class in all my Step class constructors, then tell SpecFlow’s IOC to use the same instance in every scenario:

First create the class to hold the selenium driver instance

public class SeleniumContext
{
     public SeleniumContext()
     {
          //create the selenium context
          WebDriver = new ...create the flavour of web driver you want
     }

     public IWebDriver WebDriver{get; private set;} 
}

then setup the IOC to return the same instance every time

[Binding]
public class BeforeAllTests
{
    private readonly IObjectContainer objectContainer;
    private static SeleniumContext seleniumContext ;

    public BeforeAllTests(IObjectContainer container)
    {
        this.objectContainer = container;
    }

    [BeforeTestRun]
    public static void RunBeforeAllTests()
    {
        seleniumContext = new SeleniumContext();
     }

    [BeforeScenario]
    public void RunBeforeScenario()
    {            
        objectContainer.RegisterInstanceAs<SeleniumContext>(seleniumContext );
    }
}

Then ensure your step classes always ask for the context in their constructors (you need to do this in every step class you have)

[Bindings]
public class MySteps
{
    private SeleniumContext seleniumContext;

    public MyClass(SeleniumContext seleniumContext)
    {
         //save the context so you can use it in your tests
         this.seleniumContext = seleniumContext;
    }

    //then just use the seleniumContext.WebDriver in your tests
}

alternatively if you are already storing the instance in the feature context then you can just use the BeforeFeature hook to save the same instance:

[Binding]
public class BeforeAllTests
{
    private static WebDriver webDriver;

    [BeforeTestRun]
    public static void RunBeforeAllTests()
    {
        webDriver = new WebDriver();
     }

    [BeforeFeature]
    public static void RunBeforeFeature()
    {
        FeatureContext["WebDriver"] = webDriver;
     }

}

Leave a Comment