問題描述
我嘗試練習使用 TestNG invocationCount
和 threadPoolSize
并行執行測試.
I try practicing to execute tests in parallel using TestNG invocationCount
and threadPoolSize
.
A.我這樣寫了一個一體機測試,成功了
A. I write a all-in-one test like this, and it is successful
@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瀏覽器同時打開(并行),測試成功.
=> 5 Chrome browsers are opened at the same time (parallel), and tests are successfully executed.
B.我在@before 和@after 中定義了我的測試,但它不起作用
B. I define my test in @before and @after, and it doesn't work
@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個亞馬遜詞,日志信息如下:
=> 1 chrome browser is opened, and it seems it is refreshed 5 times, and at the end, there are 5 Amazon words entered in text field, with the following log message:
[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 中相同的結果.
I understand that, with B, 5 threads use the same object driver, that's why only one chrome is opened. But I don't know how to manage driver object in this case so I can get the same result like in A.
任何想法表示贊賞.
推薦答案
你可以使用 ThreadLocal 類來讓你的 webdriver 線程安全
You can use ThreadLocal class to make your webdriver Threadsafe
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.
Edit : You will need to use BeforeMethod/AfterMethod in above context.
這篇關于Selenium 在并行運行測試時處理 ProtocolHandshake 錯誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!