

Testng Groups – Include & Exclude (Example)

TestNG is a Testing framework that covers different types of test designs like unit, functional, end-to-end, UI and integration tests.
You can run single or multiple packages (package here means to encapsulate a group of classes in a proper director format) by creating XML and running it through maven.
TestNG Groups with Example
We use groups in Testng when,
- We don’t want to define test methods separately in different classes (depending upon functionality) and
- At the same time want to ignore (not execute) some test cases as if they do not exist in the code.
- So to carry out this we have to Group them. This is done by using the “include” and “exclude” mechanisms supported in testNG.
In the example below, we have shown the syntax of how to use groups in the XML file.
Here we are using 2 group names i.e. “bonding” and “strong_ties” (these are the logical names that can be altered as per your wish).
<groups> tag defines the starting of groups in XML.
Customize your XML to pick the mentioned group from the test classes. Below mentioned is the syntax of how to declare groups in an XML file e.g.
So, let us assume that there are 10 test methods in a class.
Out of them,
- 6 methods are tagged in “bonding” group and
- 4 are in “strong_ties” group
Moving forward, we are going to set maven/Java path and use the Eclipse IDE to demonstrate the usage of groups using XML files in Java based maven project.
Create XML for TestNG with Tags
- XML (Extensible Markup Language) file in the Maven framework contains the information of one or more tests and is defined by the tag <suite> .
- Test information in XML is represented by tag <test> and can contain one or more TestNG classes.
- A Java class that contains @Test annotation above test methods is defined as TestNG methods.
Multiple tags are used in a sequence to build a working testNG xml like <suite>, <test> and <class>
- First is <suite> tag, which holds a logical name that defines full information to testNG reported to generate execution report.
- Second is <test name=”Guru 99 Smoke Test Demo”>, note it is logical name which holds the information of test execution report like pass, fail, skip test cases and other information like total time for execution and group info
- Third is <class name=” com.group.guru99.TC_Class1 ” />, com.group.guru99 is the package used, and Test Class name is TC_Class1.
We will be using this XML for the upcoming video given in the sections below.
“exclude” or “include” in test XML
Suppose you are finding the usage of group mechanism complex then testNG XML facilitate the functionality to exclude/include a test.
Note: We can include/exclude multiple test cases once at a time, which also works with Groups.
Run TestNG Group, include, exclude code (video demo)
Explanation of the Java Code and XML with the group, exclude and include the tag in XML.
Test Scenario : Launch Guru99 demo Banking site, verify few things’s on the login page after that, enter credentials, and re-verify a few new things on the application when logged in.

Note: Each step that you code should be declared in separate methods, but when executed, it will execute test methods depending upon the entries in the XML file.
- Method 1 : Initialize Browser and launch URL (tc01LaunchURL())
- Method 2 : Verify Login Page Heading (tc02VerifyLaunchPage())
- Method 3 : Enter userName and Password on login form (tc03EnterCredentials())
- Method 4 : Verify the presence of Manager ID on User Dashboard (tc04VerifyLoggedInPage())
- Method 5 : Verify few more links on User DashBoard (tc05VerifyHyperlinks())
Code for our scenario:
Please Note: The credentials are only valid for 20 days, so if you try to run code on your local machine, you might face invalid credentials error.
Explanation of Code:
As mentioned above, we have created 5 test cases for performing each action in independent methods.
For every method, we have associated a group parameter with some value.
Basically, these are the name of the differentiating groups i.e. “strong_ties” & “bonding”.
- First and Third methods are tagged to “bonding”, “strong_ties” which means if XML is updated in any of the group, this Test Case will run.
- The second method is only tagged to “bonding” group it means that if XML is updated with bonding group. Only in that case this test case will run.
- Fourth Test case is tagged to strong_ties group, which means this test case will only run if XML is updated with strong_ties group name.
- Last but not the least fifth test case is attached to bonding group, which means this test case will only run if XML is updated with bonding group name.
So overall, we have 4 scenarios;
Scenario 1: We want to run all test cases irrespective of the group name. In this case, we will remove Group tag from running XML.
Scenario 2: We want to run a few tests that are related only to either of the groups i.e. strong_ties or bonding. Please refer:
- In this video, Group parameter is commented from running XML. Hence, you will see all test cases were executed.
- In continuation to the video, now we have included group name in XML, you can see only test cases specific to that group is only running.
Scenario 3: We are using Exclude mechanism to exclude the test case. Please refer the video
- You see that we have used exclude few test case (tc02) by writing their name in running XML. In the final result, mentioned test cases did not run.
Scenario 4: Last, we are using the include test mechanism to include the test cases (tc01LaunchURL, tc03EnterCredentials, and tc05VerifyHyperlinks). Please refer the video
In this video, you will see that test cases which are mentioned in XML are only running during the test execution.
Please download the code from the code for the above example-
Download the above Code
We have learned here a relatively new way of running test cases using XML in the Maven project.
We started by providing a brief introduction to testNG and continued with the full technical specification of Groups, exclude and include.
- Flash Testing with Selenium WebDriver
- How to Verify Tooltip in Selenium WebDriver
- Selenium with Cucumber (BDD Framework)
- How to Drag and Drop in Selenium (Example)
- Selenium C# Tutorial with NUnit Example
Table of Contents
Introduction.
- Write the business logic of your test and insert TestNG annotations in your code.
- Add the information about your test (e.g. the class name, the groups you wish to run, etc...) in a testng.xml file or in build.xml.
- Run TestNG .
- A suite is represented by one XML file. It can contain one or more tests and is defined by the <suite> tag.
- A test is represented by <test> and can contain one or more TestNG classes.
- A TestNG class is a Java class that contains at least one TestNG annotation. It is represented by the <class> tag and can contain one or more test methods.
- A test method is a Java method annotated by @Test in your source.
- A list of all the annotations with a brief explanation. This will give you an idea of the various functionalities offered by TestNG but you will probably want to consult the section dedicated to each of these annotations to learn the details.
- A description of the testng.xml file, its syntax and what you can specify in it.
- A detailed list of the various features and how to use them with a combination of annotations and testng.xml.
Annotations
You can invoke TestNG in several different ways:
- With a testng.xml file
- From the command line
This section describes the format of testng.xml (you will find documentation on ant and the command line below).
The current DTD for testng.xml can be found on the main Web site: testng-1.0.dtd (for your convenience, you might prefer to browse the HTML version ).
In this example, TestNG will look at all the classes in the package test.sample and will retain only classes that have TestNG annotations.
Please see the DTD for a complete list of the features, or read on.
Running TestNG
- Command line
- IntelliJ's IDEA
Assuming that you have TestNG in your class path, the simplest way to invoke TestNG is as follows: java org.testng.TestNG testng1.xml [testng2.xml testng3.xml ...] You need to specify at least one XML file describing the TestNG suite you are trying to run. Additionally, the following command-line switches are available:
Test methods, Test classes and Test groups
Test methods, test groups.
TestNG allows you to perform sophisticated groupings of test methods. Not only can you declare that methods belong to groups, but you can also specify groups that contain other groups. Then TestNG can be invoked and asked to include a certain set of groups (or regular expressions) while excluding another set. This gives you maximum flexibility in how you partition your tests and doesn't require you to recompile anything if you want to run two different sets of tests back to back.
For example, it is quite common to have at least two categories of tests
- Check-in tests. These tests should be run before you submit new code. They should typically be fast and just make sure no basic functionality was broken.
- Functional tests. These tests should cover all the functionalities of your software and be run at least once a day, although ideally you would want to run them continuously.
will run all the test methods in that classes, while invoking it with checkintest will only run testMethod1() and testMethod2() .
Note: TestNG uses regular expressions , and not wildmats . Be aware of the difference (for example, "anything" is matched by ".*" -- dot star -- and not "*").
Method groups
Groups of groups, exclusion groups.
TestNG allows you to include groups as well as exclude them.
This way, I will get a clean test run while keeping track of what tests are broken and need to be fixed later.
Note: you can also disable tests on an individual basis by using the "enabled" property available on both @Test and @Before/After annotations.
Partial groups
TestNG allows you to pass an arbitrary number of parameters to each of your tests using the @Parameters annotation.
- The testng.xml file
- Programmatically
- Java system properties
Parameters from testng.xml
The same technique can be used for @before/after and @factory annotations:.
The @Parameters annotation can be placed at the following locations:
- On any method that already has a @Test , @Before/After or @Factory annotation.
- On at most one constructor of your test class. In this case, TestNG will invoke this particular constructor with the parameters initialized to the values specified in testng.xml whenever it needs to instantiate your test class. This feature can be used to initialize fields inside your classes to values that will then be used by your test methods.
Notes: The XML parameters are mapped to the Java parameters in the same order as they are found in the annotation, and TestNG will issue an error if the numbers don't match. Parameters are scoped. In testng.xml , you can declare them either under: <suite> tag or <test> tag or <class> tag or <methods> tag. The order of precendence (lowest to highest) in terms of resolving values for parameters with same names is <suite> --> <test> --> <class> --> <methods> If two parameters have the same name, it's the one defined in <methods> that has precedence. This is convenient if you need to specify a parameter applicable to all your tests and override its value only for certain test method.
Parameters with DataProviders
Staticprovider.java.
- An array of array of objects ( Object[][] ) where the first dimension's size is the number of times the test method will be invoked and the second dimension size contains an array of objects that must be compatible with the parameter types of the test method. This is the case illustrated by the example above.
- An array of objects ( Object[] ). This is similar to Iterator<Object[]> but causes the test method to be invoked once for each element of the source array.
- An Iterator<Object>> . Lazy alternative of Object[] . Causes the test method to be invoked once for each element of the iterator.
Parameters from System Properties
Note: In TestNG 6.x parameters defined in testng.xml could not be overwritten by system properties
Parameters in reports

Dependencies
Dependencies with annotations.
You can use the attributes dependsOnMethods or dependsOnGroups , found on the @Test annotation.
- Hard dependencies . All the methods you depend on must have run and succeeded for you to run. If at least one failure occurred in your dependencies, you will not be invoked and marked as a SKIP in the report.
In this example, method1() is declared as depending on method serverStartedOk(), which guarantees that serverStartedOk() will always be invoked first.
You can also have methods that depend on entire groups:
In this example, method1() is declared as depending on any group matching the regular expression "init.*", which guarantees that the methods serverStartedOk() and initEnvironment() will always be invoked before method1() .
Note: as stated before, the order of invocation for methods that belong in the same group is not guaranteed to be the same across test runs.
If a method depended upon fails and you have a hard dependency on it ( alwaysRun=false , which is the default), the methods that depend on it are not marked as FAIL but as SKIP . Skipped methods will be reported as such in the final report (in a color that is neither red nor green in HTML), which is important since skipped methods are not necessarily failures.
Both dependsOnGroups and dependsOnMethods accept regular expressions as parameters. For dependsOnMethods , if you are depending on a method which happens to have several overloaded versions, all the overloaded methods will be invoked. If you only want to invoke one of the overloaded methods, you should use dependsOnGroups .
For a more advanced example of dependent methods, please refer to this article , which uses inheritance to provide an elegant solution to the problem of multiple dependencies.
Dependencies in XML
Testwebserver.java, webtestfactory.java, webtest.java.
Your testng.xml only needs to reference the class that contains the factory method, since the test instances themselves will be created at runtime:
Or, if building a test suite instance programatically, you can add the factory in the same manner as for tests:
The factory method can receive parameters just like @Test and @Before/After and it must return Object[] . The objects returned can be of any class (not necessarily the same class as the factory class) and they don't even need to contain TestNG annotations (in which case they will be ignored by TestNG).
Class level annotations
Ignoring tests.
- In a class (or)
- In a particular package (or)
- In a package and all of its child packages
TestcaseSample.java
Package-info.java, parallelism and time-outs, parallel suites, parallel tests, classes and methods.
- parallel="methods" : TestNG will run all your test methods in separate threads. Dependent methods will also run in separate threads but they will respect the order that you specified.
- parallel="tests" : TestNG will run all the methods in the same <test> tag in the same thread, but each <test> tag will be in a separate thread. This allows you to group all your classes that are not thread safe in the same <test> and guarantee they will all run in the same thread while taking advantage of TestNG using as many threads as possible to run your tests.
- parallel="classes" : TestNG will run all the methods in the same class in the same thread, but each class will be run in a separate thread.
- parallel="instances" : TestNG will run all the methods in the same instance in the same thread, but two methods on two different instances will be running in different threads.
Note: the @Test attribute timeOut works in both parallel and non-parallel mode.
Rerunning failed tests
Note that testng-failed.xml will contain all the necessary dependent methods so that you are guaranteed to run the methods that failed without any SKIP failures.
- Build an implementation of the interface org.testng.IRetryAnalyzer
- Bind this implementation to the @Test annotation for e.g., @Test(retryAnalyzer = LocalRetry.class)
JUnit tests
The behavior of TestNG in this case is similar to JUnit depending on the JUnit version found on the class path:
- All methods starting with test* in your classes will be run
- If there is a method setUp() on your test class, it will be invoked before every test method
- If there is a method tearDown() on your test class, it will be invoked before after every test method
- If your test class contains a method suite(), all the tests returned by this method will be invoked
- TestNG will use the org.junit.runner.JUnitCore runner to run your tests
Running TestNG programmatically
Please see the JavaDocs for the entire API.
BeanShell and advanced group selection
If the <include> and <exclude> tags in testng.xml are not enough for your needs, you can use a BeanShell expression to decide whether a certain test method should be included in a test run or not. You specify this expression just under the <test> tag:
Here are additional information on the BeanShell script:
- It must return a boolean value. Except for this constraint, any valid BeanShell code is allowed (for example, you might want to return true during week days and false during weekends, which would allow you to run tests differently depending on the date).
- TestNG defines the following variables for your convenience: java.lang.reflect.Method method : the current test method. org.testng.ITestNGMethod testngMethod : the description of the current test method. java.util.Map<String, String> groups : a map of the groups the current test method belongs to.
- You might want to surround your expression with a CDATA declaration (as shown above) to avoid tedious quoting of reserved XML characters).
Starting from version 7.5 TestNG does not bring in any dependency on BeanShell implementations by default. So in order to leverage BeanShell based method selectors, please remember to add an explicit dependency on BeanShell. For example org.apache-extras.beanshell
Annotation Transformers
Method interceptors, testng listeners, specifying listeners with testng.xml or in java.
- First define a new custom annotation that can be used to specify this restriction: @Retention(RetentionPolicy.RUNTIME) @Target ({ElementType.TYPE}) public @interface DisableListener {}
- Add an edit check as below within your regular listeners: public void beforeInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) { ConstructorOrMethod consOrMethod =iInvokedMethod.getTestMethod().getConstructorOrMethod(); DisableListener disable = consOrMethod.getMethod().getDeclaringClass().getAnnotation(DisableListener.class); if (disable != null) { return; } // else resume your normal operations }
- Annotate test classes wherein the listener is not to be invoked: @DisableListener @Listeners({ com.example.MyListener.class, com.example.MyMethodInterceptor.class }) public class MyTest { // ... }
Specifying listeners with ServiceLoader
Dependency injection, native dependency injection, guice dependency injection, listening to method invocations, overriding test methods, altering suites (or) tests.
- Through the <listeners> tag in the suite xml file.
- Through a Service Loader
Test results
Success, failure and assert.
A test is considered successful if it completed without throwing any exception or if it threw an exception that was expected (see the documentation for the expectedExceptions attribute found on the @Test annotation).
Your test methods will typically be made of calls that can throw an exception, or of various assertions (using the Java "assert" keyword). An "assert" failing will trigger an AssertionErrorException, which in turn will mark the method as failed (remember to use -ea on the JVM if you are not seeing the assertion errors).
Here is an example test method:
Note that the above code use a static import in order to be able to use the assertEquals method without having to prefix it by its class.
Logging and results
- Listeners implement the interface org.testng.ITestListener and are notified in real time of when a test starts, passes, fails, etc...
- Reporters implement the interface org.testng.IReporter and are notified when all the suites have been run by TestNG. The IReporter instance receives a list of objects that describe the entire test run.
Logging Listeners
Logging reporters, junitreports.
Note: a current incompatibility between the JDK 1.5 and JUnitReports prevents the frame version from working, so you need to specify "noframes" to get this to work for now.
Reporter API
Reporter.log ( "M3 WAS CALLED" ) ;

XML Reports
TestNG offers an XML reporter capturing TestNG specific information that is not available in JUnit reports. This is particularly useful when the user's test environment needs to consume XML results with TestNG-specific data that the JUnit format can't provide. This reporter can be injected into TestNG via the command line with -reporter .
Here's a sample usage: -reporter org.testng.reporters.XMLReporter:generateTestResultAttributes=true,generateGroupsAttribute=true .
- : - to separate the reporter name from its properties
- = - to separate key/value pairs for properties
- , - to separate multiple key/value pairs
Below is a sample of the output of such a reporter:
This reporter is injected along with the other default listeners so you can get this type of output by default. The listener provides some properties that can tweak the reporter to fit your needs. The following table contains a list of these properties with a short explanation:
In order to configure this reporter you can use the -reporter option in the command line or the Ant task with the nested <reporter> element. For each of these you must specify the class org.testng.reporters.XMLReporter . Please note that you cannot configure the built-in reporter because this one will only use default settings. If you need just the XML report with custom settings you will have to add it manually with one of the two methods and disable the default listeners.
TestNG Exit Codes
and here is its YAML version:
Dry Run for your tests
You can enable dry run mode for TestNG by passing the JVM argument -Dtestng.mode.dryrun=true
JVM Arguments in TestNG
Back to my home page .
Or check out some of my other projects:
- EJBGen : an EJB tag generator.
- TestNG : A testing framework using annotations, test groups and method parameters.
- Doclipse : a JavaDoc tag Eclipse plug-in.
- J15 : an Eclipse plug-in to help you migrate your code to the new JDK 1.5 constructs.
- SGen : a replacement for XDoclet with an easy plug-in architecture.
- Canvas : a template generator based on the Groovy language.
Logging framework integration in TestNG
Starting from TestNG version 7.5 TestNG makes use of the logging facade provided by Slf4j. TestNG by default does not bring in any explicit Slf4j facade implementation. To control the logs being output by TestNG internals, please add a dependency on any suitable Slf4j implementation ( Native Or Wrapped implementation ) from here
- All logging is done using System.out (for levels < ERROR) or System.err. There is no way to specify Appenders.
- There is no way to control logging programmatically.
- The log4testng.properties resource is searched in the classpath on the first call to the logging API. If it is not present, logging defaults to the WARN level.
The property file contains lines in the following format: # log4testng will log its own behavior (generally used for debugging this package only). log4testng.debug=true # Specifies the root Loggers logging level. Will log DEBUG level and above log4testng.rootLogger=DEBUG # The org.testng.reporters.EmailableReporter Logger will log TRACE level and above log4testng.logger.org.testng.reporters.EmailableReporter=TRACE # All Logger in packages below org.testng will log WARN level and above log4testng.logger.org.testng=WARN In your source files you will typically instantiate and use loggers this ways: import org.testng.log4testng.Logger; class ThisClass { private static final Logger LOGGER = Logger.getLogger(ThisClass.class); ... LOGGER.debug("entering myMethod()"); ... LOGGER.warn("unknown file: " + filename); ... LOGGER.error("Unexpected error", exception);

Include and exclude in TestNG
In this post, we will discuss the include and exclude tags of TestNG in detail. Below are the points that we are going to look at in this post –

Include and exclude packages
- Second, Include and exclude test methods
- And lastly, Include and exclude groups
We can only use the <exclude> tag with the packages, methods, and run tag ( subtag of the groups that tell us which groups to run ). Let’s look at all of the points mentioned above.
In this, we will discuss packages and sub-packages and what we would need to be done to include or exclude some packages. Below is the structure that we would be using in our examples.

Here Practice is our top-level package, whereas Test1, Test2, and Test3 are our child packages, and each of them contains one Test class.
CodekruTest1.java
CodekruTest2.java
CodekruTest3.java
Now, if we want to run all of the test cases within the package Practice , we would make our XML file as shown below.
Output after running the above XML file
Include some specific packages only
Now, what if we only want to run some specific packages, like packages Test1 and Test3 ? Instead of writing the * ( asterisk ) in the XML file, we will have to write the exact path of the package that we want to run.
Exclude some specific packages only
Here we will be using the <exclude> tag to exclude some specific packages from the execution. Let’s try to exclude package Test1 from the execution.
Include and exclude test methods
This is one of the most used use case of <include> and <exclude> tags. Sometimes, we want to run only a few cases from a class instead of running all of them, and we can achieve this by using the <include> tag. And similarly, if we want to exclude some particular test cases or test methods, we can do so by using the <exclude> tag.
Include some specific test methods only
To include some of the test methods only from a test class, we have to use the <include> tag as shown below.
Let’s take a class named CodekruTest, having 4 test methods, and then we will try to run only 2 of them.
CodekruTest.java
Below is the XML file
Output after running the XML file –
Here, we can see that only test1 and test3 got executed.
Exclude some specific test methods only
The syntax of the <exclude> tag is similar to that of the <include> tag
Now, let’s exclude the test3() method from execution in the same CodekruTest class.
Output after running the XML file
Here we can see that the test3() method didn’t execute.
Include and exclude groups
We have explained TestNG groups in one of our previous articles , but we will explain the basics of including and excluding groups.
Let’s take a class that we will use to explain the inclusion and exclusion of groups in our examples.
Including specific groups
Let’s try to run the cases under group1 only
Exclude specific groups
Now, let’s try to exclude the group1. The XML file we created above will remain the same except for changing the tag name from <include> to <exclude> .
We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected] .
Leave a Comment Cancel Reply
Your email address will not be published. Required fields are marked *
Save my name, email, and website in this browser for the next time I comment.

- API Testing
- Load & Performance Testing
- QA Outsourcing
- Usability Testing
- Accessibility Testing
- UI/UX Testing
- Web Application Testing
- Selenium Automation Testing
- Appium Automation Testing
- Mobile Automation Testing
- CRM Testing
- VR & AR App Testing
- Game Testing
- AI & ML App Testing
- Blockchain Testing
- Chatbot Testing
- IoT Testing
- E-Commerce Testing
- Functional Testing
- Automation Testing
- ERP Testing
- Mobile Application Testing
- Security Testing
- Next-Gen Testing Service
What is TestNG.xml and How to use it?
Testng tutorial, recent posts.

Playwright Testing: A Practical Approach Toward E2E Testing

Agile Testing for Startups: Navigating Product Evolution with Flexibility

A Trip through QA Automation: Positive Impacts and Barriers

Game Automation Testing: Things to Consider Before You Go to Market

What is NodeJS Testing? A Comprehensive Guide
Table of content, what is testng.xml .
In TestNG framework, we need to create Testng xml file to create and handle multiple test classes. We do configure our test run, set test dependency, include or exclude any test, method, class or package and set priority etc in the xml file. TestNG.xml file is an XML file which contains all the Test configuration and this XML file can be used to run and organize our test. TestNG eclipse plugin can be used to automatically generate testng.xml file so no need to write from scratch. In this article, we are going to learn about what is testng.xml and how to use testng.xml file to run our test. TestNG support two kinds of parameterization, using @Parameter+TestNG.xml and using@DataProvider. In @Parameter+TestNG.xml parameters can be placed in suite level and test level. If the Same parameter name is declared in both places; test level parameter will get preference over suit level parameter. You understand how vital a TestNG XML file is for running parallel tests in a Selenium Grid, it is time to learn how to create a TestNG XML file. There are two methods to create a TestNG XML file, feel free to use either of them-
- Right-click on the project folder & towards the bottom of the list, select TestNG and then “Convert to TestNG.”
- Click on Next
- The next window that pops up will have the refactored source code, which would be applicable after you click Finish.
- A new addition to your project directory would be displayed named as testng.xml.
- Double click on testng.xml to open the xml file
- Right-click on Project, then New, and finally select File.
- Next, enter the following file name “testng.xml” and then click on Finish.
- In this step, you will have to enter the XML code manually. That is how the two methods differ from each other. After entering the XML code, you can select a name for your liking suite and class. This is what a basic XML file looks like-
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="Suite"> <test name="Test"> <classes> <class name="testng.TestNGTestOne"/> </classes> </test><!-- Test --> </suite><!-- Suite -->
Now you can copy the above code (with your choice of names) on the TestNG XML file we’ve created above.
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name = "Cycle1"> <test name = "QAblepoint"> <classes> <class name = "Test1" /> <methods> <exclude name= “Login.*”/> </methods> </classes> </test> </suite>
The testng.xml file has the numerous uses as listed below
- Test cases are executed in groups.
- Test methods can be included or excluded in the execution.
- The execution of multiple test cases from multiple java class files can be triggered.
- Comprises names of the folder, class, method.
- Capable of triggering parallel execution.
- Test methods belonging to groups can be included or excluded in the execution.
How to use TestNG
The hierarchy of an XML file is quite straightforward. It goes something like this- first < suite > tag, second < test > tag and lastly, < classes > tag. As mentioned above, you can give any name to the suite and test tag, but you have to be careful while naming classes since it is a combination of the Package name and Test name. Since suite is the topmost hierarchy, this is where multiple test classes can be placed. For example, we have three test classes, one for opening Google, another for searching on Google, and one to open Gmail. All these three classes can be defined under the same test tag for execution. The next step is to run the project using the XML file. Right-click on the testng.xml file and navigate to “Run As >> TestNG Suite.” You can see for yourself that the test classes mentioned in the XML ran successfully, and with it, you can now create your own test suite and run multiple tests all in one go and subsequently get the results. In our upcoming posts, we will learn about TestNG annotations along with the examples. Stay tuned and Happy TestNG! 😉
Get in touch
QAble provides you with top performing extended team. Let us know how we can help you.

Latest Blogs

How to Scale Browser Testing with Automated Testing?
.png)

Adding Classes to testng.xml file
Below are The Steps for Adding Classes to testng.xml file:
1.Create a java project with multiple classes in each package.
2.In the above project; created 3 packages called (com.test.firstpackage, com.test.secondpackage and com.test.thirdpackage) and each package had 2 classes.
3.Now create a testng.xml file (here the xml file name is “testng-classes.xml”)
with below code/configuration content.
In the above code, Classes will be reside in the “classes” tag and the each individual class will be in the “class” tag with “name” attribute.
4.Now execute the “testng-classes.xml” file from eclipse as TestNG suite. Then you can see the following output.
This way we can configure the classes in the testng xml configuration file to execute the scripts as classes and can analyse the test results.
Share this post: on Twitter on Facebook on Google+
Related Posts

Read data from Excel to DataProvider in Selenium

Running TestNG Tests Programmatically

Executing Only Failed Tests in TestNG

Capture Screenshot for Failed Tests in TestNG

Preserve Order in TestNG

Prioritizing Tests in TestNg

Execute Multiple XML files in TestNG

Custom Reporter in TestNG

Custom Logger in TestNG

TestNG Assertions

Selenium Easy
Free selenium tutorials for beginners and experts, search for selenium tutorials, testng xml example to execute with package names.
In testng.xml file we can specify the specific package name (s) which needs to be executed. In a project there may be many packages, but we want to execute only the selected packages. The below is the example testng.xml which will execute the specific packages. Example:
We need to specify the names of the packages in between the package tags. In the above xml, we have specified package name as “com.first.example” which will get executed. It will execute all the classes which have TestNG annotations Below are the two example classes under “com.first.example” package which is executed .
Classname: demoOne
Classname: demoTwo
We need to run the testng.xml file. (Right click on testng.xml and select Run as ‘TestNG Suite”)
The below is the output for the above example code.
- ‹ How to delete Cookies in Selenium Webdriver
- TestNG XML example to execute Multiple Classes ›
testng with ant
How to run only selected test cases from the testng.xml using ant.
Add new comment

IMAGES
VIDEO
COMMENTS
TestNg provides an option to include or exclude Groups, Test Methods, Classes and Packages using include and exclude tags by defining in testng.xml. First we will create an examples to use include and exclude tags for Test Methods in a class. We will create a Class with three Test Methods.
How to specify a test with method name, class name and parameters in testng.xml? Asked 6 years, 5 months ago Modified 6 years, 5 months ago Viewed 3k times 0 I wish to have test level parameters in my testng.xml and below is the code present in my testng.xml file:
Below are The Steps for Adding Methods to testng.xml file: 1.Create a java project with multiple methods in each class. In the above project, created a class called "FirstClassInFirstPackage" with three methods called "firstTestCase", "secondTestCase" and "thirdTestCase". 2.Below is the sample code for the above test class and methods. 1 2 3 4 5 6
6 methods are tagged in "bonding" group and 4 are in "strong_ties" group Moving forward, we are going to set maven/Java path and use the Eclipse IDE to demonstrate the usage of groups using XML files in Java based maven project. Create XML for TestNG with Tags
Writing a test is typically a three-step process: Write the business logic of your test and insert Add the information about your test (e.g. the class name, the groups you wish to run, etc...) in a file or in build.xml. The concepts used in this documentation are as follows: A suite is represented by one XML file.
Parallel Test Execution in TestNG: Here are some essential elements of parallel testing with TestNG in this Selenium TestNG tutorial. Creating TestNG XML File: Here is a step-by-step tutorial on creating a TestNG XML file to learn why and how it is created and discover how to run the TestNG XML file being executed in parallel.
TestNG Include and Exclude Methods | How to Include and Exclude Test Cases in TestNG in testng.xml | TestNG Include and Exclude methods, How to Include and Exclude Test Cases...
#1) A Suite is represented by one XML file. It can contain one or more tests and is defined by the <suite> tag. Example: <suite name="Testing Google Apps"> #2) A Test is represented by <test> and can contain one or more TestNG classes. Example: <test name="Regression"> #3) A Class is a Java class that contains TestNG annotations.
TestNG Include and exclude in TestNG Include and exclude in TestNG TestNG In this post, we will discuss the include and exclude tags of TestNG in detail. Below are the points that we are going to look at in this post - Include and exclude packages Second, Include and exclude test methods And lastly, Include and exclude groups
What is TestNG.xml and How to use it? By QAble Testlab Private Limited What is TestNG.xml ? In TestNG framework, we need to create Testng xml file to create and handle multiple test classes. We do configure our test run, set test dependency, include or exclude any test, method, class or package and set priority etc in the xml file.
Below are The Steps for Adding Classes to testng.xml file: 1.Create a java project with multiple classes in each package. 2.In the above project; created 3 packages called (com.test.firstpackage, com.test.secondpackage and com.test.thirdpackage) and each package had 2 classes. 3.Now create a testng.xml file (here the xml file name is "testng ...
In testng.xml file we can specify multiple name (s) which needs to be executed. In a project there may be many classes, but we want to execute only the selected classes. We can pass class names of multiple packages also. If say suppose, we want to execute two classes in one package and other class from some other package.
1 I tried to include method description in the testng.xml as follows. <class name="com.RegressionSuite"> <methods> <include name="AutTC00" **description="method desc"** /> </methods> </class> and attempted to retrieve using getDescription () method of XmlInclude
org.testng.TESTNGException: Parameter 'browser' is required by @Test on method 'testCaseOne' but has not been marked @Optional or defined in testng.xml. In testng.xml, parameter values can be set at both suite and test level. If we have two parameters with the same name, the one defined in will have the precedence. If you need to specify a ...
Steps: First Right-click on the project → TestNG → Convert to TestNG. Step to generate an XML file. 2. You will see a dialog box as shown in the picture then click on "Next". Step to ...
1 For this rather than assigning parameters in test suite xml you can assign parameters for your tests individually . for that you don't have to add each parameter in suite.xml . @Parameters ( { "datasource", "jdbcDriver" }) @test public void sampleTest (String ds, String driver) { // your test method } Hope this will help you 1
TestNG Example: How To Create And Use TestNG.Xml File Adding Methods to testng.xml file-Selenium Webdriver Appium Complete How to Configure TestNG in Selenium Java Project
5 Answers Sorted by: 61 I found better solution with @BeforeMethod annotation: import java.lang.reflect.Method; public class Test { @BeforeMethod public void handleTestMethodName (Method method) { String testName = method.getName (); ... } ... } (based on solution from this thread) Share Improve this answer Follow edited Feb 1, 2013 at 12:04
The below is the example testng.xml which will execute the specific packages. We need to specify the names of the packages in between the package tags. In the above xml, we have specified package name as "com.first.example" which will get executed. It will execute all the classes which have TestNG annotations.