Grouping Test cases in TestNG

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 scenarios 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:

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:

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:

When we add a Groups attribute to @Test annotation same attribute with same value is required in all @Before**** or @After**** annotations to execute these methods or pass an attribute alwaysRun = true in case you want before and after method to execute always irrespective of the group.

PS: For any questions queries or comment feel free to write us at or Happy Learning

Saurabh Dhingra

About the Author

Saurabh Dhingra

Follow Saurabh Dhingra: