TestNG replaces main() with a structured, professional testing framework. Add it to Maven with one dependency.
Annotation execution order: @BeforeSuite → @BeforeTest → @BeforeClass → @BeforeMethod → @Test → @AfterMethod → @AfterClass → @AfterTest → @AfterSuite. The most used pair in Selenium: @BeforeMethod (open browser) and @AfterMethod (close browser).
@Test attributes give fine-grained control: priority for order, groups for smoke/regression, dependsOnMethods for dependencies, timeOut for performance.
Hard Assert stops on first failure. Soft Assert collects all failures and reports with assertAll(). Combine both: Hard Assert for preconditions, Soft Assert for page verification.
DataProviders enable data-driven testing: one test method, many data sets. Use dataProviderClass to keep data in a separate class.
testng.xml is your suite remote control: include/exclude groups, pass parameters, configure parallel execution, register listeners.
For parallel execution, use ThreadLocal<WebDriver> to prevent thread interference. Always remove() in @AfterMethod.
ITestListener for screenshots on failure. IRetryAnalyzer for flaky test retries. Apply globally with IAnnotationTransformer.
Run with IntelliJ (development), Maven (CI/CD), or testng.xml (suites). Use testng-failed.xml to re-run only failures.
TestNG is the backbone of your automation framework. Everything we build from here — Page Object Model, data-driven testing, CI/CD integration — sits on top of TestNG. Make sure you are comfortable with every concept in this chapter before moving on.
Key Point: TestNG provides annotations, assertions, DataProviders, parallel execution, and listeners — the foundation for every professional Selenium framework.
Chapter Quiz
Answer all 5 questions, then submit to see your score.
1. What is the correct execution order of TestNG annotations?
2. What happens if you forget to call softAssert.assertAll() at the end of a Soft Assert test?
3. What does a @DataProvider method return?
4. Why must you use ThreadLocal<WebDriver> when running tests in parallel?
5. What is the difference between dependsOnMethods and priority in @Test?