How to Include and Exclude Methods in TestNG XML
By Bhau Automation β’ Master TestNG Method Inclusion & Exclusion
π― What You Will Learn
- How to use include and exclude tags in
testng.xml - How to exclude specific test methods in TestNG
- How to include only certain test cases from a class
- How to use regular expressions to include/exclude multiple methods
- Best practices for selective test execution
π‘ Pro Tip: Selective test execution using include/exclude helps optimize regression cycles and focus only on relevant tests.
π Why Include or Exclude Test Methods?
Sometimes you donβt want to execute all test cases from a class β especially in large automation suites. Using include and exclude tags inside testng.xml, you can control which methods should run and which should be skipped.
β Example: Including Specific Methods
Letβs say we have a class with multiple test methods:
import org.testng.annotations.Test;
public class LoginTests {
@Test
public void loginWithValidUser() {
System.out.println("Login with valid credentials");
}
@Test
public void loginWithInvalidUser() {
System.out.println("Login with invalid credentials");
}
@Test
public void loginWithEmptyFields() {
System.out.println("Login with empty fields");
}
}
If you only want to include loginWithValidUser and loginWithEmptyFields, your testng.xml file will look like this:
β Only the included methods will execute.
β Example: Excluding Specific Methods
Now suppose you want to skip loginWithInvalidUser. You can use exclude tag like this:
β This will execute all test methods except the excluded one.
π Using Regular Expressions
You can use regular expressions to include or exclude multiple tests with matching patterns.
β
The above regex will include all methods that start with login.
π‘ Real-World Use Case
- Running only smoke or sanity test methods
- Skipping failed or unstable test cases during quick regression
- Creating multiple XML suites for different environments (UAT, Production)
π Common Interview Questions
Q: How do I exclude a method in TestNG XML?
A: Use the tag inside the block.
Q: Can I include multiple methods from the same class?
A: Yes, by adding multiple tags inside .
Q: How do I include methods using regex in TestNG?
A: Use where pattern matches method names (e.g. login.*).
π₯ Watch the Complete Tutorial
π Watch on YouTube: How to Include & Exclude Methods in TestNG
π Related Tutorials
- What are TestNG Annotations & Framework in Selenium | Part 1
- TestNG Annotations in Selenium WebDriver | Part 2
- Parameterization in TestNG using @Parameters | Part 3
β‘ Next Steps: Practice creating multiple testng.xml files to manage include/exclude configurations effectively.
π Created with β€οΈ by Bhau Automation