Parallel execution configuration in Selenium Java - Build an Automation Script
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class LoginTest { private WebDriver driver; @BeforeMethod public void setUp() { driver = new ChromeDriver(); } @Test public void testLogin() { driver.get("https://example.com/login"); String threadName = Thread.currentThread().getName(); System.out.println("LoginTest running on thread: " + threadName); Assert.assertEquals(driver.getTitle(), "Login Page"); } @AfterMethod public void tearDown() { if (driver != null) { driver.quit(); } } } // Another test class import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class SearchTest { private WebDriver driver; @BeforeMethod public void setUp() { driver = new ChromeDriver(); } @Test public void testSearch() { driver.get("https://example.com/search"); String threadName = Thread.currentThread().getName(); System.out.println("SearchTest running on thread: " + threadName); Assert.assertTrue(driver.getTitle().contains("Search")); } @AfterMethod public void tearDown() { if (driver != null) { driver.quit(); } } } /* TestNG XML suite file (testng.xml): <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd"> <suite name="ParallelSuite" parallel="tests" thread-count="2"> <test name="LoginTest"> <classes> <class name="LoginTest"/> </classes> </test> <test name="SearchTest"> <classes> <class name="SearchTest"/> </classes> </test> </suite> */
The solution includes two separate test classes: LoginTest and SearchTest. Each class creates its own WebDriver instance in the @BeforeMethod and closes it in @AfterMethod to avoid sharing drivers between threads.
The TestNG XML suite file configures parallel execution by setting parallel="tests" and thread-count="2". This means TestNG will run the two test classes at the same time in separate threads.
Inside each test, we print the current thread name to the console to confirm parallel execution. Assertions check the page titles to verify the tests run correctly.
This setup follows best practices by isolating WebDriver instances per test and using TestNG's built-in parallel execution features.
Now add data-driven testing to LoginTest with 3 different username and password combinations