Selenium 在 运行 并行测试时处理 ProtocolHandshake 错误

Selenium handles ProtocolHandshake error while running tests parallel

我尝试使用 TestNG invocationCountthreadPoolSize 练习并行执行测试。

一个。我就这样写了一个一体机测试,成功了

@Test(invocationCount = 5, threadPoolSize = 5)
public void testThreadPool() {        
    WebDriver driver = new ChromeDriver();
    driver.get("http://www.google.com");
    driver.findElement(By.name("q")).sendKeys("Amazon");
    driver.quit();*/        
}

=> 5 Chrome 个浏览器同时打开(并行),测试成功。

乙。我在@before 和@after 中定义了我的测试,但它不起作用

@BeforeTest
public void setUp() {
   WebDriver driver = driverManager.setupDriver("chrome");
}

@Test(invocationCount = 5, threadPoolSize = 5)
public void testThreadPool() {    
    driver.get("http://www.google.com");
    driver.findElement(By.name("q")).sendKeys("Amazon");            
}

@AfterTest
public void tearDown() {
   driver.quit()
}

=> 1 chrome 浏览器打开,似乎刷新了 5 次,最后,在文本字段中输入了 5 个亚马逊单词,并显示以下日志消息:

[1593594530,792][SEVERE]: bind() failed: Cannot assign requested address (99)
ChromeDriver was started successfully.
Jul 01, 2020 11:08:51 AM org.openqa.selenium.remote.ProtocolHandshake createSession

据我了解,对于 B,5 个线程使用相同的对象驱动程序,这就是为什么只打开一个 chrome 的原因。但是我不知道在这种情况下如何管理驱动程序对象,所以我可以获得与 A 中相同的结果。

任何想法表示赞赏。

您可以使用 ThreadLocal class 使您的网络驱动程序线程安全

private ThreadLocal<WebDriver> webdriver = new ThreadLocal<WebDriver>();

   @BeforeMethod
    public void setUp() {
       webdriver.set(driverManager.setupDriver("chrome"));
    }
    
    @Test(invocationCount = 5, threadPoolSize = 5)
    public void testThreadPool() {    
        webdriver.get().get("http://www.google.com");
        webdriver.get().findElement(By.name("q")).sendKeys("Amazon");            
    }
    
    @AfterMethod
    public void tearDown() {
       webdriver.get().quit()
    }

编辑: 您需要在上述上下文中使用 BeforeMethod/AfterMethod。