简体   繁体   English

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

[英]How to reuse existing WebDriver instances in multithreading

My application is a multithreaded program. 我的应用程序是一个多线程程序。 Each thread will execute a set of test cases. 每个线程都将执行一组测试用例。 My idea is to create a new WebDriver instance for each thread and close instance when it finishes. 我的想法是为每个线程创建一个新的WebDriver实例,并在完成时关闭它。

For example: I have 100 test cases which will be executed by 10 threads. 例如:我有100个测试用例,将由10个线程执行。 Each thread takes ownership of 10 test cases. 每个线程拥有10个测试用例的所有权。

As of now for each test case a browser instance is opened. 截至目前,对于每个测试用例,都会打开一个浏览器实例。 Instead of that, for each thread a browser instance needs to be opened. 而不是那样,对于每个线程,需要打开浏览器实例。

Create your WebDriver instances using a ThreadLocal . 使用ThreadLocal创建WebDriver实例。 Quoting the JavaDoc on ThreadLocal : 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. 这些变量与它们的正常对应物的不同之处在于,访问一个变量的每个线程(通过其get或set方法)都有自己独立初始化的变量副本。 ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (eg, a user ID or Transaction ID). ThreadLocal实例通常是希望将状态与线程(例如,用户ID或事务ID)相关联的类中的私有静态字段。

Example usage: 用法示例:

// 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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