NUnit Specflow how to share a class instance for all tests

0
0

I am using Specflow with NUnit and Selenium and want to share instance of driver across all tests.
I can do do this up to feature level with FeatureContext but can’t see anything for all tests. I am aware that this is probably not the right way to go but I want to know if there is a way.

Please help with example(s).

Thanks

  • You must to post comments
0
0

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 = objectContainer;
}
[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;
}
}
  • You must to post comments
Showing 1 result
Your Answer
Post as a guest by filling out the fields below or if you already have an account.
Name*
E-mail*
Website