0
votes

I'm trying to use the same code with Appium driver and Java , TestNG but with ChromeDriver I changed the configuration by adding that code :

File file = new File("C:/QA/Emna/chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
        WebDriver driver = new ChromeDriver();

The problem is that any test case the chrome window is opened a new one, even if my tests are in a correct order with Priority (by TestNG).

Is there a way to work in only one window?

3
Instantiate 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

3 Answers

1
votes

WebDriver driver = new ChromeDriver(); is what opens a new browser each time. Move it to @BeforeClass section and use the same instance in all the tests.

1
votes

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.

0
votes

I have fixed my problem by this way in @BeforeClass:

@BeforeClass
    public static void before() {
        // check active session
        System.out.println("Becore Test Method");
        File file = new File("C:/QA/Emna/chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
        wd = new ChromeDriver();
    }

I made an instance like that:

static WebDriver driver ;

Then in every test I put the following :

@Test
public static void run1() {
//my tests using wd
}

@Test
public static void run2() {
//my tests using wd
}