[英]How to use the same Webdriver from different class
I have 2 Java classes; 我有2个Java类; Main.java and Methods.java.
Main.java和Methods.java。 At Main.java, I initialize the chrome webdriver and I want to use the same webdriver for a method at Methods.java.
在Main.java中,我初始化了chrome webdriver,并希望对Methods.java中的方法使用相同的webdriver。 Below are the codes.
以下是代码。
Under Main.java 在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 在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? 我的问题是如何从Main.java调用初始化Webdriver并在Methods.java中使用它?
Any help with be appreciated! 任何帮助,不胜感激! Thanks!
谢谢!
You can do something like this in a utility class (say TestUtil.java) 您可以在实用程序类中执行类似的操作(例如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并对其进行处理
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 : 现在,您可以像这样从方法类中调用method1:
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. 现在,一旦创建了Methods类的实例,就将调用构造函数并可以传递驱动程序引用。
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(....);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.