java 如何将驱动程序声明为全局驱动程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26411344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:53:19  来源:igfitidea点击:

How do I declare a driver as global?

javaselenium

提问by Indigo

Here is how I declare firefox driver:

这是我声明 Firefox 驱动程序的方式:

public static WebDriver driver = new FirefoxDriver();

I place the code above outside main and within my class (global)

我将上面的代码放在 main 之外和我的类中(全局)

Here is how I declare chrome driver:

这是我声明 chrome 驱动程序的方式:

System.setProperty("webdriver.chrome.driver", "/path/xxx/xxx/xx");
WebDriver driver  = new ChromeDriver();

I place the code above in main

我将上面的代码放在 main 中

Here is the issue:

这是问题:

I want to make the ChromeDriver as a global but I NEEDto set the property beforedoing so. But I place the System.setProperty("xx","xx");within the main body. Cuz it gives error when placed outside.

我想将 ChromeDriver 设为全局,但我需要在此之前设置该属性。但我把 放在System.setProperty("xx","xx");主体内。因为它放在外面时会出错。

Here is a user trying to do the same thing as me. Trying to run different browsers using the same driver : How to run Selenium tests in multiple browsers for cross-browser testing using Java?

这是一个试图和我做同样事情的用户。尝试使用相同的驱动程序运行不同的浏览器:如何在多个浏览器中运行 Selenium 测试以使用 Java 进行跨浏览器测试?

The answer is involves declaring the driver in the main body and not as a constant before.

答案是涉及在主体中声明驱动程序,而不是之前的常量。

My issue:All functions need driver declaration from before. Calling functions which use driver. If I declare driverin main, I need to continuously pass it as a parameter to all the functions. I do not wish to do that. Here is an example function

我的问题:所有函数都需要之前的驱动程序声明。调用使用driver. 如果我driver在 main 中声明,我需要不断地将它作为参数传递给所有函数。我不想那样做。这是一个示例函数

 public static void a(){

 driver.findElement(By.id("hi"));

}

回答by SiKing

How about something like:

怎么样:

class SomeTest {

    static WebDriver driver;

    public static void main(String[] args) {

        System.setProperty("key", "value");
        driver = new ChromeDriver();
    }

    public static void a() {

        driver.findElement(By.id("hi"));

    }
}