I am trying for multithreaded test via TestNG. @BeforeMethod instantiates the WebDrivers for the test @AfterMethod closes the WebDrivers after the test. @Dataprovider provides the data for the test to run multiple times in loop
import java.lang.reflect.Method;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class MultipleSession {
private WebDriver driver;
@BeforeMethod
public void beforeMethod() {
System.err.println("Before ID" + Thread.currentThread().getId());
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
if (driver == null) {
driver = new ChromeDriver();
driver.get("https://www.google.co.in/");
}
}
@DataProvider(name = "sessionDataProvider", parallel = true)
public static Object[][] sessionDataProvider(Method method) {
int len = 12;
Object[][] parameters = new Object[len][1];
for (int i = 0; i < len; i++) {
parameters[i][0] = i;
}
return parameters;
}
@Test(dataProvider = "sessionDataProvider")
public void executSessionOne(int input) {
System.err.println("Test ID" + Thread.currentThread().getId());
driver.findElement(By.name("q")).sendKeys(input + "");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@AfterMethod
public void afterMethod() {
System.err.println("After ID" + Thread.currentThread().getId());
}
@AfterSuite
public void afterSuti() {
driver.close();
driver.quit();
}
}
My problem is , Even though TestNG opens 10 browsers at a time, the tasks are carried out only by one browser while other 9 browsers do nothing. How do i distribute the instances of Webdriver declared in beforeMethod to all the threads?
Thanks in advance.
private WebDriver driver;
This line means that there is only a single instance of webdriver, driver = new ChromeDriver();
is instantiating the same driver object again and again.
To Solve this problem, create a factory and ask for driver object from the factory in every @Test method.Sample code of the factory will be something like
static synchronized RemoteWebDriver getDriver()
{
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
if (driver == null) {
driver = new ChromeDriver()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.