java - 如何在多线程中重用现有的 WebDriver 实例

标签 java multithreading selenium-webdriver

我的应用程序是一个多线程程序。每个线程将执行一组测试用例。我的想法是为每个线程创建一个新的 WebDriver 实例,并在它完成时关闭实例。

例如:我有 100 个测试用例,将由 10 个线程执行。每个线程拥有 10 个测试用例。

到目前为止,每个测试用例都会打开一个浏览器实例。相反,需要为每个线程打开一个浏览器实例。

最佳答案

使用 ThreadLocal 创建您的 WebDriver 实例.在 ThreadLocal 上引用 JavaDoc:

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

示例用法:

// for multiple separate test classes you need to share it among your project
public static final ThreadLocal<WebDriver> WEB_DRIVER_THREAD_LOCAL = 
    new ThreadLocal<WebDriver>() {
        @Override
        protected WebDriver initialValue() {
            // create a new instance for each thread
            return new ChromeDriver();
        }
    };

// get a WebDriver instance in your tests;
// when there is already an instance for the current Thread, it is returned;
// elsewise a new instance is created
WebDriver webDriver = WEB_DRIVER_THREAD_LOCAL.get();

关于java - 如何在多线程中重用现有的 WebDriver 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42066184/

相关文章:

java - 如何仅在 @AftertTest 完成后运行测试

java - Java Web App 中的上下文参数与 public static final 变量

c# - Thread Join() 导致 Task.RunSynchronously 未完成

java - runtime.getruntime.exec 无法识别可执行文件

java - 对 ExecutorService 的误解 - 我认为

java - 骡子 ESB : How the threads names are managed?

node.js - Selenium-Webdriver 错误

python - 使用 Selenium 登录网站,但继续处理(登录时)请求

java - 如何拆分字符串而不丢失任何单词?

java - WildFly jdbc 与 Oracle 的连接