TestNG Tutorials 11: How To Run TestNG class From Sub-package Using TestNG.xml?

Hello Folks,

Java allows you to group similar types of classes, interfaces and sub packages. You can create nested packages means package inside package which is termed as sub-packages.

Let’s create a below hierarchy of package:

  1. Create a Package “MainPackage”.
  2. Create a class “MainPackageClass”  in “MainPackage”
  3. Create a sub package “SubPackage” inside “MainPackage”.
  4. Create a class “SubPackageClass” in “SubPackage”.
  5. Create another sub package “SubOfSubPackage” inside “SubPackage”.
  6. Create a class “SubOfSubPackageClass” inside “SubOfSubPackage”.

You will see above hierarchy as below:

When you select “MainPackage” package and try to generate a testng.xml, you can see that it includes classes from outer package only. Not from sub packages.

Similarly, if you select any sub package and try to create a testng.xml, you will see  classes of that sub packages only not from parent package or sub package of sub package.

So, how can we make a test suite which will include all classes from package and sub packages?

You have two ways to do so.

  1. Select the Project and create testng.xml. It will include all class names from all packages and sub packages.

Problem with this approach is that it will include all other packages also which you may not want to run.

2. You can use regular expressions with package name. You can take help of <package> tag.

A. To include all sub packages of a package:  <package name=”MainPackage.*”/>

Star(*) will include all subpackages of MainPackage i.e. “MainPackage”, “SubPackage” and “SubOfSubPackage”. It will include classes “MainPackageClass”, “SubPackageClass” and “SubOfSubPackageClass.java” classes.

B. To include all classes and sub packages of a sub package: <package name=”MainPackage.SubPackage.*”/>

This will include “SubPackageClass” and “SubOfSubPackageClass.java” classes.

So, this post describes the another advantage of package tag and use of regular expression in testng.xml with package tag.

More about TestNG in upcoming posts. Stay tuned.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappySelenium

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *