Test parallelization in CI in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.time.Duration; public class ParallelLoginTest { private ThreadLocal<WebDriver> driver = new ThreadLocal<>(); @BeforeMethod public void setUp() { // Setup ChromeDriver for each thread System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); driver.set(new ChromeDriver()); } @Test(dataProvider = "loginData", threadPoolSize = 3) public void testLogin(String email, String password) { WebDriver webDriver = driver.get(); webDriver.get("https://example.com/login"); WebDriverWait wait = new WebDriverWait(webDriver, Duration.ofSeconds(10)); WebElement emailField = wait.until(ExpectedConditions.elementToBeClickable(By.id("email"))); emailField.clear(); emailField.sendKeys(email); WebElement passwordField = webDriver.findElement(By.id("password")); passwordField.clear(); passwordField.sendKeys(password); WebElement loginButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("loginBtn"))); loginButton.click(); // Wait for dashboard URL wait.until(ExpectedConditions.urlContains("/dashboard")); String currentUrl = webDriver.getCurrentUrl(); Assert.assertTrue(currentUrl.contains("/dashboard"), "User should be redirected to dashboard"); } @DataProvider(name = "loginData", parallel = true) public Object[][] loginData() { return new Object[][] { {"user1@example.com", "Password1!"}, {"user2@example.com", "Password2!"}, {"user3@example.com", "Password3!"} }; } @AfterMethod public void tearDown() { driver.get().quit(); driver.remove(); } }
This test class uses TestNG and Selenium WebDriver to run login tests in parallel.
We use ThreadLocal<WebDriver> to ensure each test thread has its own browser instance, avoiding interference.
The @DataProvider supplies three sets of login credentials and is marked parallel=true to enable parallel execution.
The @Test method uses explicit waits to ensure elements are ready before interacting, improving reliability.
Assertions check that after login, the URL contains '/dashboard', confirming successful login.
Finally, @BeforeMethod and @AfterMethod setup and clean up the WebDriver instances per test thread.
This setup is suitable for running in a CI environment configured to run TestNG tests in parallel.
Now add data-driven testing with 3 different user credentials to run in parallel