Reputation: 1825
I try practicing to execute tests in parallel using TestNG invocationCount
and threadPoolSize
.
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 browsers are opened at the same time (parallel), and tests are successfully executed.
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 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
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.
Any idea appreciated.
Upvotes: 0
Views: 381
Reputation: 4349
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()
}
Edit : You will need to use BeforeMethod/AfterMethod in above context.
Upvotes: 1