gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:36:10 26 4
gpt4 key购买 nike

我的应用程序是一个多线程程序。每个线程将执行一组测试用例。我的想法是为每个线程创建一个新的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com