'Would it be the right approach to close and open a new WebDriver session between negative tests in Selenium?

I close my driver and reopen it between each negative test, for example - in my negative login test - if the test failed it means the login succeeded, then I close the driver and open it again so I start from a fresh browser in the login page again.

Is it best practice to do it that way? I thought about some alternatives but I can't decide which one is better -

  1. closing the driver only when I actually need to - for example when the test failed and it logged in.
  2. clear the browser cache and cookies between each test, so it'll simulate new driver.


Solution 1:[1]

Of course, a test has to start with a fresh session or you can get test bugs that will hard to reproduce. You can use Selenoid (https://aerokube.com/selenoid/latest/), you will get a new browser each time faster. To deploy it locally use https://docs.docker.com/docker-for-windows/install/

Solution 2:[2]

I would recommend not to restart the browser each time unless it is required in your test to have a fresh instance .

This is because users won't be always using fresh browser instant for each buissnesss requirement flow (Or test case ).

So for end to end test you can use the same browser instance

Solution 3:[3]

From a broader perspective, while performing or tests the pre-requites of a testcase remains the same. So there is no harm in continuing the tests in the same browsing context.

However, during negative testing it would be a better idea to start each testcase through a fresh browsing context so the tests fails for the proper reason else you may face a lot of False positives and false negatives due to unwanted cookies and other session attributes.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ilya Tatsiy
Solution 2 PDHide
Solution 3 undetected Selenium