简体   繁体   中英

How to use the same Webdriver from different class

I have 2 Java classes; Main.java and Methods.java. At Main.java, I initialize the chrome webdriver and I want to use the same webdriver for a method at Methods.java. Below are the codes.

Under Main.java

Methods getMethods = new Methods();

    @BeforeTest
    public void Setup()
    {
        System.setProperty("webdriver.chrome.driver", "C:\\...\\chromedriver.exe");

        driver = new ChromeDriver();

        driver.get(PropertiesConfig.getObject("websiteUrl"));

        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);          
    }

  @Test
        public void TestCase1()
        {
          getMethods.method1();
        }


@AfterTest
    public void QuitTC() {
        getMethods.QuitTC(); }

Under Methods.java

    public void method1 (){
                  driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        …..  }

    public void QuitTC() {
        driver.quit();
    }

My question is how do I called the initialize Webdriver from Main.java and used it at Methods.java?

Any help with be appreciated! Thanks!

You can do something like this in a utility class (say TestUtil.java)

private static WebDriver wd;

public static WebDriver getDriver() {
    return wd;
}

and then you can use following line to get the webdriver in any of the classes mentioned and work on it

WebDriver driver = TestUtil.getDriver();

Declare a global variable for driver like this :

WebDriver driver = null; 

@BeforeTest
public void Setup()
{
    System.setProperty("webdriver.chrome.driver", "C:\\...\\chromedriver.exe");

    driver = new ChromeDriver();

    driver.get(PropertiesConfig.getObject("websiteUrl"));

    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);          
}  

Now, you can call method1 from method class like this :

public class Methods{

 public Methods(WebDriver driver){
      this.driver = driver; 
  }

public void method1 (){
                  driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        …..  }
}   

Now once you create the instance of Methods class, constructor would be called and driver reference could be passed.

Try this

    Class1 {
    public WebDriver driver = null;
    public String baseURL="...";

    public void openURL() {
    System.setProperty("webdriver.chrome.driver", "D:...\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.get(baseURL);
    }

    Class2 extends Class1 {
    driver.findElement(....);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM