Adsterra Native banner 4:1

TestNG Parallel Execution

Parallel execution in TestNG allows you to run multiple test methods, classes, or test cases simultaneously, which reduces the execution time significantly, especially helpful for regression suites or large test sets.


Why Parallel Execution?

  • Improves execution speed

  • Optimizes resource usage

  • Useful for Cross-Browser testing or multi-user simulation


How to Do Parallel Execution in TestNG

You can do parallel execution in TestNG by configuring the testng.xml file with the parallel attribute.


Supported values for parallel attribute:

methods – Run test methods in parallel

tests – Run different <test> tags in parallel

classes – Run test classes in parallel

instances – Run multiple instances of test class in parallel


Folder Structure

/project

 ├─ /src

 │   ├─ ParallelTest1.java

 │   └─ ParallelTest2.java

 └─ testng.xml



Java Test Classes

ParallelTest1.java

import org.testng.annotations.Test;

public class ParallelTest1 {
    @Test
    public void testMethodOne() {
        System.out.println("Test Method One - Thread ID: " + Thread.currentThread().getId());
    }
}



ParallelTest2.java

import org.testng.annotations.Test;

public class ParallelTest2 {
    @Test
    public void testMethodTwo() {
        System.out.println("Test Method Two - Thread ID: " + Thread.currentThread().getId());
    }
}



testng.xml Configuration

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name="ParallelTestSuite" parallel="classes" thread-count="2">
    <test name="Test1">
        <classes>
            <class name="ParallelTest1" />
            <class name="ParallelTest2" />
        </classes>
    </test>
</suite>


How it Works

  • The parallel="classes" means that ParallelTest1 and ParallelTest2 will run in parallel.

  • The thread-count="2" allows 2 threads to run simultaneously.

  • Each test method prints its Thread ID to confirm they are running in separate threads.



Output

Test Method One - Thread ID: 15
Test Method Two - Thread ID: 16


Important Points

  • Make sure your code is thread-safe (example: no shared mutable data) if you're using parallel execution.

  • Avoid using static variables unless they're synchronized or thread-local.

  • Combine with DataProviders if testing with different data in parallel.

No comments:

Post a Comment