NUnit Specflow how to share a class instance for all tests

后端 未结 1 643
清酒与你
清酒与你 2020-11-28 13:16

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 an

相关标签:
1条回答
  • 2020-11-28 13:31

    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;
         }
    
    }
    
    0 讨论(0)
提交回复
热议问题