Selenium 简明教程

Selenium WebDriver - ThreadGuard

ThreadGuard 类仅适用于 Java Binding。它用于确保从其起始线程调用驱动程序。在并行模式下运行测试时会遇到 * Multiple Threading* 问题,有时这些问题不容易调试并找出错误的根本原因。在 ThreadGuard wrapper 的帮助下,我们可以避免这些问题,并在适当的时候生成正确的异常。

The ThreadGuard class is only applicable to Java Binding. It is used to ensure that a driver is invoked from the same thread from where it originated. Multiple Threading problems are encountered while running the tests in parallel mode, and those are sometimes not very easy to debug and find the root cause of the errors. With the help of the ThreadGuard wrapper, we can avoid those issues and generate the correct exception at the proper time.

Example

public class DriverParallel {

   //Thread main (id 1) created this driver
   private WebDriver pDriver = ThreadGuard.protect(new EdgeDriver());

   //Thread-1 (id 14) is calling the same driver resulting in error
   Runnable run1 = () -> {
      protectedDriver.get("https://www.tutorialspoint.com/selenium/practice/accordion.php");
   };
   Thread thread1 = new Thread(run1);

   void runThreads(){
      thread1.start();
   }

   public static void main(String[] args) {
      new DriverClash().runThreads();
   }
}

以上代码会产生异常。在此,pDriver 将在主线程中创建。Runnable 类用于引入新进程和新线程。两个都会遇到问题,因为主线程的内存中没有 pDriver。因此,threadGuard.protect 会生成异常。

The above code would give an exception. Here, the pDriver would be created in the Main thread. The Runnable class is used to introduce a new process and a new thread. Both of them would encounter issues since the main thread is devoid of pDriver in its memory. Hence threadGuard.protect would generate an exception.

因此,在本教程中,我们讨论了使用 Selenium WebDriver 的 ThreadGuard。

Thus, in this tutorial, we had discussed ThreadGuard using the Selenium Webdriver.