seleniumselenium-webdrivertestng

Should I initiate WebDriver in BeforeClass or BeforeTest in TestNG


I'm still learning about automation testing and i've been looking through some testing framework. I see there are 2 approaches to where people initiate WebDriver.

  1. Some are initiating it in BeforeClass (using TestNG), it keeps the driver alive for the whole class testing, including many test cases.
  2. Other groups initiate WebDriver inside each of the test case @Test or @BeforeTest, so that they can have new WebDriver for every class.

Where is the right place that we need to initiate the WebDriver? Thank you.


Solution

  • There is no such thing as "right place"!

    If you initiate the driver from @BeforeClass, then the same one browser will be available to every test in that class - including any session cookies and other history. Each of the tests needs to account for the state that the previous test left your app in. For example: it is a good idea to perform login to your app in @BeforeTest and logout from your app in @AfterTest.

    If you initiate the driver from @BeforeTest, then you will be starting with a clean browser session for every single test. This is slower (due to the browser being started for every test), but is much cleaner as you do not have to worry what state the previous test left your browser in.