Introduction to TestNG: Features, Annotations, and Maven Integration
This article introduces TestNG, an open‑source Java testing framework, outlines its key features and annotations, demonstrates how to set it up in Maven, and provides detailed code examples for basic annotations, suite configuration, test grouping, and disabling tests.
TestNG is an open‑source Java testing framework inspired by JUnit and NUnit, offering advanced features such as flexible annotations, test groups, dependency management, parallel execution, and a powerful plugin API.
Key features include annotation‑driven tests, support for class‑level and method‑level configuration, test suites, groups (e.g., fast, slow, database), dependent tests, multithreaded execution, and extensible plugins.
Setting up TestNG with Maven requires adding the following dependency to pom.xml :
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
<scope>compile</scope>
</dependency>
</dependencies>Basic TestNG annotations are demonstrated in the BasicAnnotation class, showing the execution order:
BeforeSuite → BeforeClass → BeforeMethod → Test1 → AfterMethod → BeforeMethod → Test2 → AfterMethod → AfterClass → AfterSuiteThe class includes examples of @Test , @BeforeMethod , @AfterMethod , @BeforeClass , @AfterClass , @BeforeSuite , and @AfterSuite annotations, each printing a message to illustrate when they run.
Suite configuration is shown with SuiteConfig , LoginTest , and PayTest classes, together with a suite.xml file that defines two tests (login and pay) and includes the suite configuration class.
To disable a test , add enabled = false to the @Test annotation; omitting the attribute defaults to true .
Method grouping is illustrated with the GroupsOnMethod class, where tests are assigned to "server" or "client" groups using @Test(groups = "...") , and @BeforeGroups / @AfterGroups run setup/teardown code for each group.
Class grouping is demonstrated by annotating entire classes with @Test(groups = "...") . Three example classes ( GroupsClass1 , GroupsClass2 , GroupsClass3 ) belong to groups "stu" and "teacher" and contain simple methods that print messages.
The corresponding groupsClass.xml file shows how to run all classes or selectively include only the "stu" group.
Throughout the article, images illustrate IDE steps for creating a module, adding Maven dependencies, and configuring test suites.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.