• Selenium Video Tutorials

Selenium WebDriver - 執行緒保護



ThreadGuard 類僅適用於 Java 繫結。它用於確保驅動程式從其起源的同一執行緒呼叫。在並行模式下執行測試時會遇到多執行緒問題,而且這些問題有時不容易除錯並且難以找到錯誤的根本原因。藉助 ThreadGuard 包裝器,我們可以避免這些問題並在適當的時間生成正確的異常。

示例

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://tutorialspoint.tw/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 將引發異常。

因此,在本教程中,我們討論了使用 Selenium Webdriver 的 ThreadGuard。

廣告

© . All rights reserved.