TestNG Annotations in Selenium Java – Practical Guide with Execution Flow
By Bhau Automation • Learn TestNG Annotations Practically in Selenium
🎯 What You Will Learn in This Video
- What is a TestNG annotation?
- Exact use of TestNG annotations in Selenium automation
- How many annotations are available in TestNG?
- How to use TestNG annotations practically
- TestNG annotations execution flow & sequence
- Common TestNG interview questions
💡 Pro Tip: Proper understanding of TestNG annotations sequence helps you avoid flaky tests and improves framework stability.
📌 What is a TestNG Annotation?
TestNG Annotations are Java annotations (starting with @) that control how and when your Selenium test methods execute. They define the lifecycle of your test framework including setup, execution, and teardown.
🔧 Exact Use of TestNG Annotations
- ✅ Initialize browser and environment
- ✅ Control test execution order
- ✅ Handle preconditions and post-conditions
- ✅ Group and prioritize test cases
- ✅ Support data-driven testing
📋 TestNG Annotations Covered in This Tutorial
| Annotation | Purpose |
|---|---|
@BeforeSuite | Execute once before entire test suite |
@AfterSuite | Execute once after entire test suite |
@BeforeTest | Runs before |
@AfterTest | Runs after |
@BeforeClass | Runs before first test method in class |
@AfterClass | Runs after all methods in class |
@BeforeMethod | Runs before each @Test |
@AfterMethod | Runs after each @Test |
🔄 TestNG Annotations Execution Flow
Order: @BeforeSuite → @BeforeTest → @BeforeClass → @BeforeMethod → @Test → @AfterMethod → @AfterClass → @AfterTest → @AfterSuite
💻 Practical Example (Selenium + TestNG)
import org.testng.annotations.*;
public class TestNGFlowDemo {
@BeforeSuite
public void setupSuite() {
System.out.println("BeforeSuite - Setup reports");
}
@BeforeClass
public void launchBrowser() {
System.out.println("BeforeClass - Launch Browser");
}
@BeforeMethod
public void beforeEachTest() {
System.out.println("BeforeMethod - Navigate to URL");
}
@Test
public void loginTest() {
System.out.println("Test - Login Test");
}
@AfterMethod
public void afterEachTest() {
System.out.println("AfterMethod - Logout");
}
@AfterClass
public void closeBrowser() {
System.out.println("AfterClass - Close Browser");
}
@AfterSuite
public void teardownSuite() {
System.out.println("AfterSuite - Generate Report");
}
}
❓ Common Interview Questions
Q: What is TestNG annotation?
A: Annotations define the execution flow and lifecycle of test methods in TestNG.
Q: How many annotations are in TestNG?
A: TestNG provides multiple annotations such as BeforeSuite, AfterSuite, BeforeTest, AfterTest, BeforeClass, AfterClass, BeforeMethod, AfterMethod, Test, DataProvider, etc.
🎥 Watch the Complete Video Tutorial
👉 Watch on YouTube: TestNG Annotations in Selenium Java Practical Tutorial
🚀 Created with ❤️ by Bhau Automation