Parallel Execution of test methods in TestNG
TestNG provides multiple ways to execute tests in separate threads. In testng.xml, if we set 'parallel' attribute on the tag to 'tests', testNG will run all the ‘@Test’ methods in tag in the same thread, but each tag will be in a separate thread.
If we want
to run methods/classes in separate threads, we need to set 'parallel' attribute
on the tag to 'methods' / 'classes'
TestNG provides an ability to run test methods, test
classes and tests in parallel. By using parallel execution, we can reduce the
'execution time' as tests are started and executed simultaneously in different
threads.
**A
thread is an independent path of execution within a program. Every thread in
Java is created and controlled by the java.lang.Thread class.
Let’s Consider the below example:
package
pack1;
import
org.testng.annotations.Test;
public class
ParallelTestId {
@Test
public void
testCaseOne() {
System.out.println("Test
Case One with Thread Id:- "+ Thread.currentThread().getId());
}
@Test
public void
testCaseTwo() {
System.out.println("Test
Case two with Thread Id:- "+ Thread.currentThread().getId());
}
}
If you will
run the above program, you will get the output as below.
[TestNG] Running:
C:\Users\Sujoy\AppData\Local\Temp\testng-eclipse-1521962657\testng-customsuite.xml
Test Case One with
Thread Id:- 1
Test Case two with Thread Id:- 1
From the above output you can observe that both the
test methods are running under one thread. i.e. Under Thread id 1
If you want to run independent test methods in
multiple threads, then you have to configure your testng.xml file as below.
We are defining two attributes 'parallel'
and 'thread-count' at suite level.
As we want test methods to be executed in parallel, we have provided 'methods'.
And 'thread-count' attribute is to use to pass the number of maximum threads to
be created.
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Parallel test suite" parallel="methods" thread-count="2">
<test name="Regression 1">
<classes>
<class name="pack1.ParallelTestId"/>
</classes>
</test>
</suite>
If you will
run the above testng.xml file, you will get the output as below.
[TestNG] Running:
E:\HardDisk\Sujoy\ SampleProject\testng.xml
Test Case One with
Thread Id:- 11
Test Case two with Thread Id:- 12
The above
result shows that two methods executed using different threads. When we run the
same testng.xml again, the result may vary. The assigning of the thread is take
care by the processor. So we can't say which thread is going to execute which
method.
No comments:
Post a Comment