You need to move you code snippet in any @Before
type of TestNG methods. Lets say your all test cases are in a TestNG
class then
Here is how it should look like:
@BeforeClass
public void deSetup(){
File file = new File("C:/QA/Emna/chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driver = new ChromeDriver();
}
But if this is not the case, what I mean by this, that your test cases are spread across the multiple TestNG classes then the best way is to have a Singleton
class to load and initialize the ChromeDriver. Call method of the Singleton
class to instantiate the ChromeDriver in any one of method annotated as @BeforeSuite
@BeforeTest
or @BeforeGroups
. And have a reference variable of WebDriver
type in evelry test class and assigne the previously initialized ChromeDriver to this reference variable in @BeforeClass
method.
In such a way, ChromeDriver will be instantiated only once when any one of @BeforeSuite
@BeforeTest
or @BeforeGroups
method runs and will be available in every TestNG class once @BeforeClass
runs.
This way you can work in only one Chrome window.
ChromeDriver
once and use it until you are done with you test cases execution. Eg:WebDriver driver = new ChromeDriver();
can be in any method annotated as@BeforeSuite
,@BeforeTest
,@BeforeGroups
or@BeforeClass
. – Atul Dwivedi