Maintain and re-use existing webdriver browser instance - java

前端 未结 4 1364
不思量自难忘°
不思量自难忘° 2021-01-16 03:19

Basically every time I run my java code from eclipse, webdriver launches a new ie browser and executes my tests successfully for the most part. However, I have a lot of test

4条回答
  •  死守一世寂寞
    2021-01-16 03:46

    I have tried the below steps to use the same browser instance and it worked for me:

    If you are having generic or Class 1 in different package the below code snippet will work -

    package zgenerics;
    
    import java.io.IOException;
    import java.util.concurrent.TimeUnit;
    
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.testng.annotations.BeforeTest;
    import org.openqa.selenium.WebDriver;
    

    // Class 1 :

    public class Generics  {
    
    public Generics(){}
    
    protected WebDriver driver;
    
    @BeforeTest
    
    public void maxmen() throws InterruptedException, IOException{ 
    driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
        String appURL= "url";
        driver.get(appURL);
        String expectedTitle = "Title";
        String actualTitle= driver.getTitle();
        if(actualTitle.equals(expectedTitle)){
            System.out.println("Verification passed");
        }
        else {
            System.out.println("Verification failed");
        } }
    

    // Class 2 :

    package automationScripts;
    import org.openqa.selenium.By;
    import org.testng.annotations.*;
    import zgenerics.Generics;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    public class Login extends Generics {
    @Test
    public void Login() throws InterruptedException, Exception {
    WebDriverWait wait = new WebDriverWait(driver,25);
    
       wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("")));
       driver.findElement(By.cssSelector("")).sendKeys("");
    
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("")));
        driver.findElement(By.xpath("")).sendKeys("");
    
    }
    }
    

    If your Generics class is in the same package you just need to make below change in your code:

    public class Generics  {
    
    public Generics(){}
    
    WebDriver driver; }
    

    Just remove the protected word from Webdriver code line. Rest code of class 1 remain as it is.

    Regards, Mohit Baluja

提交回复
热议问题