How to run tests in parallel in Selenium WebDriver in TestNg
- Dev Raj Sinha
- Nov 3, 2023
- 2 min read
Running tests in parallel is a great way to reduce test execution time and speed up the feedback loop in your automated testing process. Selenium WebDriver provides multiple options for parallel execution. Here, I'll explain how to run tests in parallel using TestNG, a popular testing framework for Java.
Prerequisites:
1. Java Installed: Ensure you have Java Development Kit (JDK) installed on your machine.
2. TestNG: You can add TestNG to your project either via your build tool (such as Maven or Gradle) or by downloading the TestNG JAR and adding it to your project.
Parallel Execution with TestNG:
TestNG allows you to run tests in parallel by specifying the parallel mode in your TestNG XML configuration file. Here's how you can set up parallel execution:
Step 1: Create a TestNG XML Configuration File
Create a TestNG XML file (e.g., `testng.xml`) and define your test suite and test classes. Specify the `parallel` attribute to define how you want your tests to run in parallel. For example, you can parallelize by classes, methods, or tests.
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="MyTestSuite" parallel="tests" thread-count="3">
<test name="Test1">
<classes>
<class name="com.example.TestClass1" />
</classes>
</test>
<test name="Test2">
<classes>
<class name="com.example.TestClass2" />
</classes>
</test>
</suite>
In this example, tests `Test1` and `Test2` will run in parallel with a thread count of 3.
Step 2: Update Your Test Classes
In your test classes, annotate your test methods with `@Test`. Ensure your tests are thread-safe, especially if they share state.
import org.testng.annotations.Test;
public class TestClass1 {
@Test
public void testMethod1() {
// Test code
}
}
public class TestClass2 {
@Test
public void testMethod2() {
// Test code
}
}
Step 3: Run Your Tests
You can run your tests using the TestNG XML file. Use your IDE or run TestNG from the command line:
java -cp "path/to/testng.jar:path/to/your/classes" org.testng.TestNG testng.xml
Replace `"path/to/testng.jar"` with the path to the TestNG JAR file, and `"path/to/your/classes"` with the path to the compiled classes of your project.
TestNG will execute the tests specified in the XML file in parallel as per the configuration.
Remember to handle synchronization and avoid shared states among your tests to ensure thread safety when running tests in parallel. TestNG's parallel execution feature is powerful, but it requires careful consideration of your test design to avoid unexpected interactions between tests.
Comments