What is TestNG: Advantages, Annotations, & Best Practices

On This Page What is TestNGAdvantages of TestNGJune 06, 2026 · 14 min read · Testing Guide

What is TestNG: Advantages, Annotations, & amp; Best Practices

TestNG simplifies test conception, deal execution flowing, and support advanced features like parallel testing, grouping, and parameterization.

Overview

What is TestNG

TestNG is an open-source Java Testing testing framework for automation testing. It is built on the foundation of JUnit and NUnit.

Beneficial Features of TestNG

  • Annotations Support
  • Parameterization
  • Configuration via testng.xml
  • Dependency Management
  • Parallel Execution
  • HTML Reporting

TestNG Annotations

  • @ BeforeSuite
  • @ AfterSuite
  • @ BeforeClass
  • @ AfterClass
  • @ BeforeTest
  • @ AfterTest
  • @ BeforeGroups
  • @ AfterGroups
  • @Test
  • @ BeforeMethod
  • @ AfterMethod
  • @ Parameters
  • @ Listeners

Learn what is TestNG, how to execute it, the good practices and more with this elaborate guide.

What is TestNG

TestNG is one of the most wide used open-source testing frameworks utilise in the automation testing suite. This framework is establish upon the foot of JUnit and NUnit thus introducing some new functionalities that make it more powerful and easier to use.

TestNG allows you to easy specify test case dependencies, notation, group, test sequencing and data-driven testing.

Advantages of TestNG

Below are some of the advantages of TestNG:

  • TestNG supports annotations (such@ BeforeSuite, @ AfterSuite, @ BeforeTest, etc.) which you can use to define methods and the executing order.
  • TestNG supports parameterization, which allows you to run the same method with different set of data. It has built-in support for data-driven testing, which allows you to fetch information from external root such as CSV files, Excel sheets, etc.
  • Through testing.xmlfile, TestNG let you to configure the test cases to define specific dependencies among test method, parallel execution of examination methods/classes/tests, grouping of test cases, parameterization and many more.
  • To ensure tryout cases are executed in a specific order based on their dependencies, TestNG can be used to define such configurations with the help of “dependsOnMethods” and “dependsOnGroups”.
  • TestNG can be expend to run test methods/classes/tests/suites to run in parallel mode which can importantly reduce the overall test performance time.
  • TestNG can be used to generate elaborate HTML reports which comprise point such as examination resolution, execution clip, logarithm, etc. These story are super easy to interpret and analyze.
  • TestNG can be well integrated with build tools such as Maven/ Ant and continuous integration instrument such as Jenkins.

TestNG vs JUnit: Core Differences

TestNG and JUnit are frameworks that integrate with Selenium

JUnitTestNG
It is open-source test frameworkIt is open-source Java based testing framework
It supports unit testingIt supports unit, functional, integrating, and end-to-end testing
It perform not support advanced annotations such as@ BeforeGroups and @ AfterGroupsIt supports innovative annotation such as@ BeforeGroups and @ AfterGroups
It uses @RunWith, @Suite to run the trial suiteIt uses an XML file to run the test suite
It does not indorse dependency in test casesIt supports dependency in test case by usingdependsOn and dependsOnGroupattributes with@ Test annotating
It make not support grouping of test casesIt indorse grouping and execution of exam cases together
It can be integrated with Maven to generate HTML reportsIt has built-in HTML story
It supports listeners through Listeners APIIt indorse hearer through note
It has limited support for parallel executionIt has built-in support for parallel executing at various levels such as methods/classes/tests

TestNG Annotations

TestNG notation provide a way to control the execution of tests and are apply to delimit the behaviour and configuration of test methods and test classes. A special symbol “@” is used followed by the name of the annotation.

Below are the note widely used in TestNG.

  1. @ BeforeSuite:Method consort with this annotation will run before the performance of all the examination methods in the rooms.
  2. @ AfterSuite:Method consociate with this notation will run after the execution of all the test method in the suite.
  3. @ BeforeClass:Method colligate with this annotating will be executed before the first @ Test method execution.
  4. @ AfterClass:Method connect with this annotation will be executed after all test methods in the current class have been run.
  5. @ BeforeTest:The annotated method will run before any test method of the class inside the & lt; test & gt; tag
  6. @ AfterTest:Method relate with this annotation will be executed when all the @ Test annotate method finish the execution of those classes inside the & lt; test & gt; tag in the testing.xml file.
  7. @ BeforeGroups:This method will run before the first test run of that particular radical merely once.
  8. @ AfterGroups:This method will run after all the test methods of that specific grouping discharge their execution.
  9. @Test:This annotation depute a method as a test case. You can specify additional characteristics, highlight dependencies, and enable or deactivate tests using this note.
  10. @ BeforeMethod:@ BeforeMethod allows the method to execute before the performance of each @ Test method.
  11. @ AfterMethod:@ AfterMethod is executed after the executing of each @ Test method.
  12. @ Parameters:This note is used to pass parameter from the testing.xml file or from other sources into the test methods.
  13. @ Listeners:This annotation is utilise to specify one or more listener course for the test entourage that should be alerted of test events.

Read More:

What is a Test entourage in TestNG?

In TestNG, a test suite is defined with the & lt; suite & gt; element in a special configuration file called testng.xml.

This XML file outlines which test form or methods should be run together. The suiteXmlFile attribute specifies the name and positioning of this contour file, which act as the pattern for executing a grouping of test example.

Unlike test cases defined in the source code, a suite is not write in Java. it survive purely for execution design and offers a flexible way to configure test execution.

The & lt; suite & gt; tag is the root component of the testng.xml file. It can contain one or more & lt; test & gt; subdivision, each representing a set of grade or methods to be run.

Here are all the legal property that the& lt; suite & gt;tag accepts in TestNG & # 8217; stestng.xml file:

AttributeDescription
nameThe name of the test cortege.
verboseSets the verbosity stage of logging (0 to 10).
parallelDefines how to run tests in latitude. Values: tests, class, method, etc.
thread-countSpecifies the number of threads to use for parallel execution.
data-provider-thread-countSets the number of threads for data providers.
annotationsAllows using JDK 5 annotations or Javadoc (values: JDK, Javadoc).
configfailurepolicyDefines behavior when a configuration method fails (skip or continue).
group-by-instancesIf true, methods from the same instance are aggroup together in parallel footrace.
preserve-orderIf true, maintain the order of & lt; test & gt; factor during execution.
skipFailedInvocationCountsIf true, skips counting failed invocations multiple times.
allow-return-valuesIf true, allows test method to return values.

How to Create a Test Suite in TestNG

To make a examination retinue in TestNG, you need to write an XML form file named testng.xml.This file defines which test classes or method should be executed together.

Step 1: Create Your Test Classes

Create Java class with TestNG test methods via annotations like @ Test.

// Example: LoginTest.java importation org.testng.annotations.Test; public stratum LoginTest {@ Test public void loginWithValidUser () {System.out.println (`` Login successful '');}}

Step 2: Create the testng.xml File

This XML file outlines your test cortege and the tests to run.

& lt;! DOCTYPE cortege SYSTEM `` https: //testng.org/testng-1.0.dtd '' & gt; & lt; suite name= '' MyTestSuite '' & gt; & lt; test name= '' FunctionalTests '' & gt; & lt; category & gt; & lt; class name= '' com.example.tests.LoginTest '' / & gt; & lt; course name= '' com.example.tests.SearchTest '' / & gt; & lt; /classes & gt; & lt; /test & gt; & lt; /suite & gt;

Step 3. Test Suite Execution

Run the suite utilize:

IDE (like IntelliJ or Eclipse): For this you can right-click testng.xml → Run as → TestNG Suite

Command Line:

java -cp `` path-to-testng-jar; your-compiled-classes '' org.testng.TestNG testng.xml

How To Create A TestNG XML File To Execute TestNG Test Suites?

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

The testng.xml file is used to configure and manage examination execution in TestNG. It delimit the test suite, specifies the test classes or package to be run.

Step 1. Create Your Test Classes

Ensure the test classes use TestNG annotations like @ Test.

// File: LoginTest.java significance org.testng.annotations.Test; public class LoginTest {@ Test populace void validLogin () {System.out.println (`` Login successful '');}}
// File: SearchTest.java signification org.testng.annotations.Test; public class SearchTest {@ Test public void searchProduct () {System.out.println (`` Search successful '');}}

Step 2: Create the testng.xml File

Create this file manually in your undertaking directory.

& lt;! DOCTYPE suite SYSTEM `` https: //testng.org/testng-1.0.dtd '' & gt; & lt; suite name= '' MyTestSuite '' & gt; & lt; test name= '' AppTests '' & gt; & lt; classes & gt; & lt; class name= '' LoginTest '' / & gt; & lt; class name= '' SearchTest '' / & gt; & lt; /classes & gt; & lt; /test & gt; & lt; /suite & gt;

Step 3: Place the XML File in Your Project

Place the file at the root point or in a resources folder, depending on the project construction.

Step 4. Execute the XML Suite File

Run the testng.xml file expend command line

java -cp `` path-to-testng-jar; bin '' org.testng.TestNG testng.xml

Why use TestNG with Selenium?

TestNG is primarily utilise for contemporaries of reports that provide elaborate info regarding number of test cases executed, passed, betray and skipped count, duration of each test case execution, and logarithm. Along with reporting it also provides style to check the executing flow, test assertions, parallelisation, parameterization of tests etc.

Selenium does not have an inbuilt mechanism to give exam reports. Therefore, TestNG is expend to render comprehensive report.

TestNG besides aid to line how the test cases should be write in a integrated manner using different annotations.

Apart from these two there are several other reasons as well which are name below:

  • TestNG provides a set of annotations such as@Test, @ BeforeTest, @ AfterTest, @ BeforeClass, @ AfterClass, etc which render control over the test methods execution. It besides helps in configurations such as setting up pre-conditions and logically grouping the tests.
  • TestNG allows you to organise trial into cortege and group which aids in managing large test projects.
  • For speeding up the execution time of turgid tryout suites, TestNG supports parallel executing. You can configure parallel exam execution at the test, form or method tier.
  • With TestNG ’ s@ DataProvidernotation you can provide data to your examination methods. This is beneficial if you want to run the same tests with different sets of data.
  • TestNG allows setting dependencies between tests using annotations. This is good in cases where certain tests should only run if other examination hold passed.
  • TestNG can be integrated with build tools such as Maven and Gradle which simplifies the process of extend examination as part of the build process and aid in generating reports.

Read More:

Prerequisites of TestNG

To get started with TestNG below are some prerequisites you should be familiar with:

  1. Get familiar with the basics of Software Testing which will aid you understand the concepts of test cases, tryout execution, and different types of testing.
  2. As TestNG is a Java based examine framework, you should be familiar with Java concepts such as OOPs, basic programming, and elision manipulation
  3. You should be familiar with any IDE (Integrated Development Environment) such as Eclipse, IntelliJ which have mix support for TestNG.

How to run TestNG in Selenium: Example

To run TestNG in Selenium, you involve to follow a few stairs to set up the environment and make the test scripts.

Pre-requisites of extend TestNG in Selenium

  1. Java 8 or any higher version should be installed.
  2. Eclipse or any similar IDE establish.
  3. Maven installed.

Steps to run TestNG in Selenium:

Step 1. Install TestNG plugin in Eclipse:

  • Open Eclipse IDE, click onHelpselection & gt;Install New Software.
  • Click on the “Add” button on the “Install” window. Enter “Name” as “TestNG” and “Location” as “https: //testng.org/testng-eclipse-update-site”. Click on the “Add” button.
  • This URL will fetch the latest TestNG plugin detail from the TestNG website for installation. Make certain to take all the checkboxes and click on Next push to proceed with induction. Click on the “Next” button.
  • Click on the “I accept” checkbox and chink on the “Finish” button.
  • Check the “https: //testng.org” check box and pawl on the “Trust Selected” push to proceed.
  • Once the frame-up is complete it will remind to restart the IDE. After re-start the IDE, you can control the TestNG instalment by right tick on importedMaven project > Build Path > Configure build path. Click on the “Add Library” button, select TestNG and detent on “Next” and then “Finish” button.

Step 2. Add TestNG and Selenium Java habituationin Maven ’ spom.xmlfile under dependencies tag. Save thepom.xmland control the dependency are list under Maven Dependencies.

& lt; dependence & gt; & lt;! -- https: //mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -- & gt; & lt; dependency & gt; & lt; groupId & gt; org.seleniumhq.selenium & lt; /groupId & gt; & lt; artifactId & gt; selenium-java & lt; /artifactId & gt; & lt; version & gt; 4.23.0 & lt; /version & gt; & lt; /dependency & gt; & lt;! -- https: //mvnrepository.com/artifact/org.testng/testng -- & gt; & lt; dependence & gt; & lt; groupId & gt; org.testng & lt; /groupId & gt; & lt; artifactId & gt; testng & lt; /artifactId & gt; & lt; adaptation & gt; 7.10.2 & lt; /version & gt; & lt; /dependency & gt; & lt; /dependencies & gt;

Step 3. Create the TestNG tryout case.

  • Create a Maven project and undersrc/test/java,create a examination bundle. Create a grade under test bundle as “LaunchBrowser
packagetestcases;importorg.openqa.selenium.By;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importorg.testng.Assert;importorg.testng.annotations.AfterClass;importorg.testng.annotations.BeforeClass;importorg.testng.annotations.Test;public classLaunchBrowser {WebDriver driver; @ BeforeClasspublic voidframe-up () {driver =newChromeDriver (); driver.get (`` https: //www.browserstack.com/ '');} @ Test (priority = 1)public voidverifyTitle () {Assert.assertEquals(driver.getTitle (), `` Most Reliable App & amp; Cross Browser Testing Platform | BrowserStack '');} @ Test (precedency = 2)public voidverifyGetStratedFree () {WebElement logo = driver.findElement (By.cssSelector(`` header # header-habitat a [title='BrowserStack Logo '] img '')); String logoImg = logo.getAttribute (`` src ''); Assert.assertNotEquals(logoImg, `` '');} @ AfterClasspublic voidtearDown () {driver.quit ();}}

@ BeforeClass and @ AfterClassnote are used for setup and tear down methods respectively.@Testannotation is used with priority attribute to assign the priority for each tryout causa and therefore “verifyTitle” will run before “verifyGetStratedFree” as it has priority value as “1”.

Step 4. Run the TestNG test case

To run the test case, flop detent on “LaunchBrowser” and select “Run As” > “TestNG Test”. The examination case will run and you can see the TestNG Result.

Step 5. Create testing.xml file to run suite of exam case

If there is a suite of examination cases,testing.xmlfile can be used which help in configuring and running the test causa.

To run a suite of exam case, make a testing.xml file by correct chatter on the test lawsuit from package explorer, and so select “TestNG” > Convert to TestNG.

Click on the “Finish” button and insure that the testing.xml file is created under the root directory of the project.

Step 6. Run the testing.xml file

Right click on the testing.xml file and select “Run As” > “TestNG suite

Best Practices of TestNG

Below are some of the best practices to follow when using TestNG:

1. :To run tests with different comment, use@ Parameters and @ DataProviderwhich helps in reduce code duplication and enhances test coverage.@ DataProvidercan also be used to furnish multiple sets of data to a test method.

2. Implement:To speed up the test executing and run examination in parallel, you can use testing.xml file to configure. You can specify parallel execution at the method, test or suite level in the testing.xml

3. Implement:To customise test performance, log and describe you must use ITestListener and ITestResult. It help in get screenshots on failures and sending notifications.

4. Organize testcases with groups:TestNG groups allow you to do grouping of different test methods. You should use groups when you desire to entree the examination methods of different classes. Groups can be specified either in the & lt; suite & gt; tag or & lt; examination & gt; tag.

5. Use annotations wisely:To control the test execution order and dependencies, use@Testannotation for exam method with attribute such as “priority” and “dependsOnMethods”. You should also use@ BeforeSuite, @ AfterSuite, @ BeforeClass, @ AfterClass, @ BeforeTest and @ AfterTestannotations for setup and teardown methods.

6. Use Assertions:TestNG ply various affirmation method such asassertEquals, assertNotEquals, assertTrue, assertFalse, etc. Make use of these assertions to control the test solvent.

7. Implement reporting:TestNG helps to generate testing reports for the test execution. These can be integrated with Allure and Extent Report for more detailed and customised test reports.

Why run TestNG Tests on BrowserStack Automate?

TestNG is a popular and most widely used testing framework for Selenium mechanisation, as it provides ways to publish the test cases in proper order, and facilitate in parallel executing and report generation.

If you run TestNG tests on, it will increase the scalability and reduce the maintenance of trial cause. BrowserStack provides admittance to a wide-eyed reach of devices, browsers and operating scheme to test your applications across different environments without needing to maintain complex infrastructure.

BrowserStack Automate has built-in support for TestNG making it easier to configure and run your test cases.

Talk to an Expert

Conclusion

TestNG is a potent testing framework that simplifies tryout configuration, executing, and report for Java applications. With flexible test cortege management via XML files and features like annotations, parallel execution, test grouping etc, TestNG ease an easy-to-build, knock-down and maintainable machine-controlled test rooms.

You can advance increase the scalability and reduce the maintenance of test suit lead your TestNG test on BrowserStack Automate.

Utile Resources for TestNG

Tags
17,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free