Teardown of Multiple Threaded Tests with Selenium



  • I'm trying to run multiple test cases with Nunit in C# in which every test needs its own Selenium Chrome Driver.

    Before it was threaded, I handled the chrome driver with [Setup] and [Teardown] like so:

    [TestFixture]
    [SingleThreaded]
     public class MyThreadedTest
    {
        private IWebDriver _driver;
    
        [SetUp]
        public void Setup()
        {
            _driver = new ChromeDriver();
            _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
        }
    
        [TearDown]
        public void Teardown()
        {
            _driver?.Quit();
        }
    ...
    

    Now, however, I'm using [Parallelizable(ParallelScope.All)] instead of [SingleThreaded].

    This means that all of my test cases that happen below that will all attempt to use the same Chrome Driver, instead of spawning a new one for each session.

    A solution to this problem would be to do the setup and tear down in the actual test case, but then I don't get the nice tear down function that I've come to love with Nunit, because the driver will wind up being out of scope.

    So my question is this: Is there a way to handle threaded setup and tear down in a more graceful way? I'm looking for some way to handle threaded setup and teardown; similar to what this answer touches on.



  • You can try using the ThreadLocal Class, so each running thread would be assigned it's own webdriver instance.

    See pseudocode to get the idea:

    private static readonly ThreadLocal<IWebDriver> WebDrivers = new ThreadLocal<IWebDriver>();
    
    public static IWebDriver Instance
    {
        get
        {
            if (WebDrivers.Value == null)
            {
                Log.Warn("Please call method 'Start' before can get Driver");
            }
    
            return WebDrivers.Value;
        }
    
        set => WebDrivers.Value = value;
    }
    
    public static void Start()
    {
        WebDrivers.Value = new ChromeDriver();
    }
    


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2