How can a particular group of test cases get executed in TestNG?
In TestNG, executing a particular group of test cases is made easy with the group's feature, which allows you to categorize and organize your tests. By assigning test methods to specific groups and configuring TestNG’s XML file, you can selectively run only the relevant test cases, such as sanity, regression, or integration tests. This approach enables efficient test execution, especially for large test suites, by focusing on the necessary subset of tests without running the entire suite.
Steps to create and execute a particular group of test cases in TestNG
Following are the steps to create and execute a particular group of test cases in TestNG:
Step 1: Create a test class
Create a test class in any IDE that contains test cases.
Step 2: Grouping Test Cases with the group's Attribute
Test methods can be assigned to groups by using the groups attribute inside the @Test annotation.
In this example:
- testCase1 is assigned to the sanity group.
- testCase2 is assigned to the regression group.
- testCase3 is assigned to both sanity and regression groups.
GroupedTestCases.java
import org.testng.annotations.Test;
public class GroupedTestCases {
@Test(groups = { "sanity" })
public void testCase1() {
System.out.println("Sanity Test - Test Case 1");
}
@Test(groups = { "regression" })
public void testCase2() {
System.out.println("Regression Test - Test Case 2");
}
@Test(groups = { "sanity", "regression" })
public void testCase3() {
System.out.println("Sanity and Regression Test - Test Case 3");
}
}
Step 3: Configuring check groups within the TestNG XML file
Groups to be executed can also be specified in the TestNG XML configuration file. By using the <groups> tag, you can define which groups of test cases should be included or excluded during execution. Here’s how to include only the sanity group
In this example: The <include> tag inside <groups> specifies that only the sanity group should be executed.
testng.xml
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Test Suite">
<test name="Sanity Tests">
<groups>
<run>
<include name="sanity"/>
</run>
</groups>
<classes>
<class name="GroupedTestCases"/>
</classes>
</test>
</suite>
Step 4: Executing Multiple Groups
If you want to execute multiple groups at once (e.g., sanity and regression), modify the XML file to include both groups. This configuration will run all test cases belonging to either the sanity or regression groups.
testng.xml
<groups>
<run>
<include name="sanity"/>
<include name="regression"/>
</run>
</groups>
Output:

Conclusion
In TestNG, the groups function offers flexibility in managing and executing tests. By using the groups attribute in your test methods and configuring the TestNG XML file, you can control which specific tests are executed. Whether you’re running sanity tests or regression tests, TestNG groups make your test suite more modular and manageable.