Quick TestNG Reference Guide for Java/Selenium
(Concepts, Code Examples, Best Practices & Real-World Usage)
– Ranjit Appukutti
1. Introduction
TestNG (Test Next Generation) is a powerful testing framework for Java inspired by JUnit and NUnit,
but designed to support modern automation requirements such as parallel execution, data-driven
testing, flexible configuration, and rich reporting.
When combined with Selenium WebDriver, TestNG becomes the execution engine of a robust
automation framework—controlling test lifecycle, sequencing, data flow, and integration with CI/CD
pipelines.
This guide is a comprehensive, end-to-end reference covering TestNG from basics to advanced
framework-level concepts with practical Selenium examples.
2. Setting Up TestNG with Selenium
Maven Dependencies ([Link])
<dependencies>
<!-- TestNG -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>testng</artifactId>
<version>7.8.0</version>
<scope>test</scope>
</dependency>
<!-- Selenium WebDriver -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>selenium-java</artifactId>
<version>4.15.0</version>
</dependency>
<!-- WebDriverManager -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.6.2</version>
</dependency>
</dependencies>
Gradle Dependencies
dependencies {
testImplementation '[Link]:testng:7.8.0'
testImplementation '[Link]:selenium-java:4.15.0'
testImplementation '[Link]:webdrivermanager:5.6.2'
Why these dependencies matter
• TestNG → Test execution lifecycle & orchestration
• Selenium → Browser automation
• WebDriverManager → Automatic driver management (industry standard today)
3. TestNG Annotations Explained
3.1 @Test Annotation
The core annotation that marks a method as a test case.
@Test
public void testLogin() {
[Link]("Executing login test");
Commonly used attributes:
• priority – Execution order (use cautiously)
• description – Test documentation
• timeOut – Performance constraint
• enabled – Skip test
• dependsOnMethods – Logical flow
@Test(priority = 1)
public void testHomePage() { }
@Test(priority = 2)
public void testDashboard() { }
@Test(description = "Verify user can login with valid credentials")
public void testValidLogin() { }
@Test(timeOut = 5000)
public void testWithTimeout() { }
@Test(enabled = false)
public void testUnderDevelopment() { }
Best Practice:
Avoid priority for business flows.
Use dependencies to express real application behavior.
4. Test Lifecycle Annotations (Critical Concept)
Understanding the TestNG lifecycle is essential for framework design.
Execution Order:
@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
@Test
@AfterMethod
@AfterClass
@AfterTest
@AfterSuite
5. @BeforeMethod & @AfterMethod
Runs before and after each test method.
@BeforeMethod
public void setUp() {
[Link]().setup();
driver = new ChromeDriver();
[Link]().window().maximize();
@AfterMethod
public void tearDown() {
if (driver != null) {
[Link]();
When to use
• Fresh browser per test
• Independent tests
• Parallel execution safety
6. @BeforeClass & @AfterClass
Runs once per test class.
@BeforeClass
public void setUpClass() { }
@AfterClass
public void tearDownClass() { }
When to use
• Shared browser session
• Sequential test flows
7. @BeforeSuite & @AfterSuite
Runs once per entire suite.
@BeforeSuite
public void setUpSuite() {
// Reports, DB connections, environment setup
@AfterSuite
public void tearDownSuite() {
// Cleanup resources
Never initialize WebDriver here
8. Complete Selenium + TestNG Example
Your example demonstrates:
• Explicit waits
• Assertions with messages
• Clean setup & teardown
Key insight:
TestNG decides WHEN tests run
Selenium decides HOW actions happen
9. Data-Driven Testing with @DataProvider
Basic DataProvider
@DataProvider(name = "loginData")
public Object[][] getLoginData() {
return new Object[][] {
{"user1@[Link]", "password123"},
{"user2@[Link]", "password456"}
};
}
@Test(dataProvider = "loginData")
public void testLogin(String username, String password) { }
Why DataProvider?
• Clean separation of logic & data
• Each dataset appears as a separate test
• Scales well for large test suites
10. External Data Sources (CSV / Excel)
Enterprise automation uses external test data.
Benefits:
• No code changes for data updates
• Business-friendly
• CI/CD compatible
@DataProvider(name = "csvData")
public Object[][] getCsvData() throws IOException { }
11. Test Dependencies
@Test
public void testLogin() { }
@Test(dependsOnMethods = "testLogin")
public void testDashboard() { }
Behavior:
• If parent fails → dependent tests are SKIPPED, not FAILED
Used for:
• Login → Dashboard → Logout
• Setup → Execute → Cleanup
12. Groups (Smoke, Regression)
@Test(groups = {"smoke"})
public void testLogin() { }
Used for:
• CI pipelines
• Release gating
• Selective execution
13. Parallel Execution
Parallel execution improves speed but requires thread safety.
private static ThreadLocal<WebDriver> driver = new ThreadLocal<>();
Why ThreadLocal?
• One browser per thread
• No conflicts
• Grid-ready execution
Parallel execution without ThreadLocal = flaky tests
14. [Link] – Execution Control Center
Basic Example
<suite name="Selenium Test Suite">
<test name="Login Tests">
<classes>
<class name="[Link]"/>
</classes>
</test>
</suite>
Parallel Execution
<suite name="Parallel Suite" parallel="methods" thread-count="3">
XML defines what runs & how, code defines what to test.
15. Parameters & Cross-Browser Testing
@Parameters({"browser", "url"})
@BeforeMethod
public void setup(String browser, String url) { }
Used for:
• Chrome / Firefox / Edge
• QA / Stage / Prod
16. Assertions in TestNG
Hard Assertions
• Stop execution immediately
• Critical validations
Soft Assertions
• Continue execution
• Report all failures at the end
SoftAssert softAssert = new SoftAssert();
[Link](condition);
[Link]();
17. TestNG Listeners
Listeners hook into execution events.
Used for:
• Logging
• Screenshots
• Reporting
• Notifications
public class CustomTestListener implements ITestListener { }
18. Screenshot Capture on Failure
Implemented via listeners to improve debugging and reporting.
19. Page Object Model (POM)
Principles:
• Page classes → Actions only
• Test classes → Assertions only
Benefits:
• Maintainability
• Reusability
• Cleaner tests
20. Retry Logic
public class RetryAnalyzer implements IRetryAnalyzer { }
Used for flaky tests only.
Retry is a temporary shield, not a fix.
21. Base Test Class (Framework Backbone)
Centralizes:
• Driver setup
• Waits
• Browser configuration
Every professional framework has a BaseTest.
22. End-to-End (E2E) Example
Your E2E test demonstrates:
• Business flow modeling
• Dependencies
• Groups
• Stability
This is interview-ready framework proof.
23. Running Tests from Command Line
Maven
mvn test
mvn test -DsuiteXmlFile=[Link]
mvn test -Dgroups=smoke
Gradle
gradle clean test
24. Conclusion
TestNG is not just a testing framework—it is the orchestration engine of modern automation.
By combining:
• TestNG
• Selenium
• Data-driven testing
• Parallel execution
• Listeners & reporting
• Page Object Model
You can build scalable, maintainable, CI/CD-ready automation frameworks.