Cucumber (Java) 和 Selenium:使用 setProperty 在哪里放置驱动程序路径?

Cucumber (Java) and Selenium: where to place driver path using setProperty?

我正在使用 Cucumber 为 Java 和 Selenium 构建一个测试套件。我的项目结构几乎是这样的:

现在,我所做的是在 src/test/java 中添加一个 Hooks.java class,使用 @Before 钩子来设置驱动程序路径:

@Before
public void setUpDriver(){
    System.setProperty("webdriver.chrome.driver", "src\test\resources\seleniumdrivers\chromedriver.exe");
}

但是,由于这个方法会在每个场景之前运行,我想找到一个更好的方法来设置路径,所以只做了一次。请注意,我希望在我的项目结构中包含驱动程序并使用系统 属性 对其进行设置(我的意思是,我不想将驱动程序放置在我的文件系统中的某个位置并将其添加到 PATH 环境变量中) .

有更好的方法吗?

您可以将驱动程序保存在您的项目文件夹中,并使用 System.getProperty

获取该项目路径

您可以尝试以下代码:-

 String path= System.getProperty("user.dir");

  System.setProperty("webdriver.chrome.driver", path+"\src\test\resources\test\chromedriver.exe");

因为您不想将它添加到 PATH 环境变量,您可以将 chromedriver 二进制 文件系统中的任何地方(包括src\test\resources\seleniumdrivers\)并且仍然可以在System.setProperty()中指定如下:

@Before
public void setUpDriver(){
    System.setProperty("webdriver.chrome.driver", ".\src\test\resources\seleniumdrivers\chromedriver.exe");
}

您可以创建一个 属性 文件,如 config.properties 来存储您在整个执行过程中使用的所有全局值以及 chromedriver.exe 的路径,并在所有场景和之前读取它像这样在整个执行过程中使用。

public class Hooks {
    private static boolean beforeSuit = true;
    private static String executablePath;
    static Properties prop;

    @Before
    public void beforeAll() {
        if(beforeSuit) {
            prop = new Properties();
            ClassLoader loader = Thread.currentThread().getContextClassLoader();           
            InputStream stream = loader.getResourceAsStream("/config.properties");
            prop.load(stream);
            //You can use this anywhere you want to launch the chrome.
            executablePath = prop.getProperty("executablePath");
            //To make it execute only once
            beforeSuit = false;

            //If you wish to launch browser only once , you can have that code here.
        }

        //Here you can keep code to be execute before each scenario

    }
}

如果您使用 Maven,请在您的 pom.xml 中添加这两个依赖项,您会没事的,现在您可以删除 System.setProperty 行。使用这种技术,项目的硬编码方法更少。

 <dependency>
        <groupId>io.github.bonigarcia</groupId>
        <artifactId>webdrivermanager</artifactId>
        <version>3.3.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.6.2</version>
        <scope>test</scope>
    </dependency>

你还需要添加这一行来设置它

        WebDriverManager.chromedriver().setup();