Parallel Execution of Methods In TestNG
Parallel execution of tests in TestNG will discuss about the ability of executing the test methods in parallel based on the test suite configuration. Different thread will start simultaneously and the test methods will be executed in those threads. This will reduce the execution time while running the multiple test methods as a suite. You can achieve this functionality in different ways using the testng.xml file configuration.
Executing test methods in Parallel:
Below is the sample Code:
import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class methodParallelExecution { @BeforeMethod public void beforeMethod() { System.out.println("In before method"); } @Test public void testOne() { System.out.println("In testOne"); } @Test public void testTwo() { System.out.println("In testTwo"); } @AfterMethod public void afterMethod() { System.out.println("In after method"); } }
The above program contains two test methods and those will print some console message. And those contains @BeforeMethod and @AfterMethod annotation to which will be useful to print the some messages before and after execution of the each test method execution.
Now create a testng.xml file to execute the above methods as parallel.
Below is the sample code:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="Suite" parallel="methods" thread-count="2"> <test name="Test"> <classes> <class name="methodParallelExecution"/> </classes> </test> </suite>
In the above XML file, we have created a suite and then we have assigned some attributes to that suite. One is “parallel” this attribute accepts a value called “methods” and second is “thread-count” and it accepts value as integers. When you execute this xml file then it executes the tests in parallel mode as we have configured that in the xml file. It will create 2 threads to execute the tests in parallel.
Now we will see the execution with and without parallel then we can come to know the difference:
1.Without Parallel execution:
Just remove the parallel and thread-count attributes from the testng.xml file and execute the same then we can find the below output:
2.With Parallel execution:
Add Parallel and thread-count attributes to the testng.xml file and then execute the same then we can find the below output:
From the above outputs, we can observe that when you use parallel and thread-count attributes both the tests started parallelly and executed. This way we can configure the testng.xml file to execute the tests parallelly. By using this mechanism we can reduce the execution time while executing the test suite which will contain more number of tests.
Please watch the youtube video for better understanding.