Sharing the webdriver across multiple step definition classes in SpecFlow

In this topic we will see how to share the same driver instance across multiple step definition classes. Consider below feature file.

Feature: Sharing data

@sharing
Scenario: Sharing Data Scenario 1
	Given I am on the page "https://www.softpost.org"
	Then I verify that title of the web page contains "free tutorial"

 

Then we have created a shared class. In this class, we can keep data or objects that we want to share among step definition classes. In below class, we are just sharing webdriver.

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TechTalk.SpecFlow;

namespace SpecFlowRunnerProject
{
    public class MySharedThings
    {
        public IWebDriver driver;

      
    }
}

 

Then we have created below Base Class. All step definition classes will inherit this class. Note that we have passed the instance of above class in the constructor.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Firefox;
using System;
using TechTalk.SpecFlow;

namespace SpecFlowRunnerProject
{
    public class BaseStep
    {
        protected MySharedThings things;

        public BaseStep(MySharedThings sharedThings) {
            this.things = sharedThings;
        }

        [BeforeScenario("sharing")]
        public void before()
        {
           things.driver = new FirefoxDriver();
        }     

        [AfterScenario("sharing")]
        public void after()
        {
            things.driver.Close();
            things.driver.Quit();
        }

    }
}

 

After this we have below step definition class. This is where we access the share driver. To share the driver in other step definition classes, all you have to do is inherit BaseStep class.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Firefox;
using System;
using TechTalk.SpecFlow;

namespace SpecFlowRunnerProject
{
    [Binding]
    public class SharingDataSteps : BaseStep
    {
        public SharingDataSteps(MySharedThings sharedThings) : 
            base(sharedThings)
        {
        }

        [Given(@"I am on the page ""(.*)""")]
        public void GivenIAmOnThePage(string p0)
        {
            things.driver.Navigate().GoToUrl(p0);
        }
        
        [Then(@"I verify that title of the web page contains ""(.*)""")]
        public void ThenIVerifyThatTitleOfTheWebPageContains(string p0)
        {
            Assert.IsTrue(things.driver.Title.ToLower().Contains(p0));
        }
    }
}

You may also like...