Grouping Test cases in TestNG

August 21, 2016

TestNG provides an excellent feature of Grouping Test cases. Let us consider a scenario where we have 5 features to test and in the project, we have 5 Java Classes, one for each feature. and we want to execute all the Sanity test cases of all these 5 features. This can be handled using Groups attribute with @Test annotation.

Let us learn Grouping with an example. Consider below two classes TestClass1 and TestClass2 which have 2 test cases with group = “Sanity” each.

Code of TestClass1:

Code of TestClass2:

Now to execute only “Sanity” test cases of both these classes we will write a testng.xml file, we can include and exclude any group in an xml file.

Result after running above testng.xml file:

[TestNG] Running:
C:\workspace\LearningSelenium\src\com\qatechhub\testng\package1\testng.xml

Executing testcase2 of testclass1..
Executing testcase4 of testclass1..
Executing testcase1 of testclass2..
Executing testcase3 of testclass2..

Here, only Sanity Test cases of both the classes are executed.

Excluding a Group from Execution:

We can also exclude a group from execution. Say for example in above scenario, if we want to skip all Sanity Test cases. we can use below testng.xml file for the same.

After execution result is as below:

[TestNG] Running:
C:\workspace\LearningSelenium\src\com\qatechhub\testng\package1\testng.xml

Executing testcase1 of testclass1..
Executing testcase3 of testclass1..
Executing testcase2 of testclass2..
Executing testcase4 of testclass2..

Multiple Group Execution:

Multiple groups can be included or excluded from a run. See below code:

Here, in above code tc2() method is a part of both “Sanity” and “Regression” group and it will be executed if any of the group is executed.

Multiple Groups can be included or excluded from testng.xml file. See below code:

PS: For any questions queries or comment feel free to write us at saurabh@qatechhub.com or support@qatechhub.com. Happy Learning

Saurabh

About the Author

Saurabh

Follow Saurabh:

Leave a Comment: