Selenium

How to Include and Exclude Methods in TestNG XML | Selenium Java Tutorial

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

Next Steps: Practice creating multiple testng.xml files to manage include/exclude configurations effectively.

🚀 Created with ❤️ by Bhau Automation