TestNG Annotations : Part 3 - rohitkrbhardwaj09/TestNG_ByRSA GitHub Wiki

📊 TestNG Annotations: @BeforeSuite, @AfterSuite, @BeforeMethod, @AfterMethod, @BeforeClass, @AfterClass, and Groups


🔹 @BeforeSuite & @AfterSuite

❓ What is a Suite in TestNG?

  • In TestNG XML, the <suite> tag wraps all `` blocks.
  • It represents the entire test suite (project-level).

✅ Purpose:

Annotation Purpose
@BeforeSuite Runs once before any test classes/methods in the suite.
@AfterSuite Runs once after all tests in all test folders.

📄 Example Use Cases:

  • Set global environment variables (e.g., ENV=QA, URL=https://test-env.com)
  • Start Appium Server before any mobile test execution
  • Load base URL or API tokens
  • Initialize global reports/logs

💼 Real-Time Examples:

  • Selenium WebDriver: Load global browser config or reporting setup before starting any test cases.
  • REST Assured API Testing: Load API keys or tokens once before tests and clean up after the entire suite.
  • Appium: Start the Appium server at the beginning and stop it at the end of the suite.

📂 Sample Code:

@BeforeSuite
public void setupSuiteEnv() {
    System.out.println("I am number one (BeforeSuite)");
    // Load config.properties, establish DB connection
}

@AfterSuite
public void tearDownSuiteEnv() {
    System.out.println("I am the number one from last (AfterSuite)");
    // Flush extent reports or close DB connection
}

🔹 @BeforeMethod & @AfterMethod

❓ What is a Method in TestNG?

Each test case in a class is a Java method annotated with @Test.

✅ Purpose:

Annotation Purpose
@BeforeMethod Runs before every test method in a class
@AfterMethod Runs after every test method in a class

📄 Example Use Cases:

  • Clear cookies (before/after each test)
  • Re-authenticate API keys for each API test
  • Open/Close browser tabs per test
  • Reset environment or user state before every test case

💼 Real-Time Examples:

  • Selenium WebDriver: Delete cookies and clear session before each test.
  • REST APIs: Refresh auth tokens or reset request headers.
  • Mobile Automation: Restart app or clear storage between each test.

📂 Sample Code:

@BeforeMethod
public void beforeEachTest() {
    System.out.println("Before every test method");
    // Example: driver.manage().deleteAllCookies();
}

@AfterMethod
public void afterEachTest() {
    System.out.println("After every test method");
    // Example: driver.quit(); or logout()
}

🔹 @BeforeClass & @AfterClass

✅ Purpose:

Annotation Purpose
@BeforeClass Executes once before any test method in class
@AfterClass Executes once after all test methods

📄 Example Use Cases:

  • Launch browser before executing tests in class
  • Set up database connections or configurations
  • Log class-wide test setup

💼 Real-Time Examples:

  • Selenium: Launch browser once and reuse it for all tests in that class.
  • REST Assured: Authenticate with server once for the class scope.
  • Appium: Start and stop session for class-based tests.

📂 Sample Code:

@BeforeClass
public void setupClass() {
    System.out.println("Before executing any method in the class");
    // driver = new ChromeDriver();
}

@AfterClass
public void tearDownClass() {
    System.out.println("After executing all the methods in the class");
    // driver.quit();
}

🔹 Groups in TestNG

✅ Purpose:

  • Execute a subset of test methods grouped logically
  • Useful for creating suites like Smoke, Regression, Sanity

📄 How to Use:

1. Tag test methods:

@Test(groups = {"Smoke"})
public void loginTest() {
    System.out.println("Smoke test method");
}

2. Reference group in XML:

<test name="Smoke Test">
    <groups>
        <run>
            <include name="Smoke"/>
        </run>
    </groups>
    <classes>
        <class name="test.day1.Day1Tests" />
        <class name="test.day2.Day2Tests" />
        <class name="test.day3.Day3Tests" />
    </classes>
</test>

💼 Real-Time Example:

  • Client wants to run only 4 critical Smoke test cases every build
  • These are scattered across multiple classes
  • Tag them with @Test(groups = {"Smoke"})
  • Use <include name="Smoke"/> in XML

🚫 Common Mistakes

  • Assuming @BeforeMethod runs once — it runs before every test method.
  • Thinking @AfterSuite waits for other files — it only runs after entire suite.
  • Confusing XML scope (suite/test) with class/method scope.
  • Forgetting that method execution order is alphabetical by default.

🌟 Real-World Comparison Table

Annotation Executes... Scope Type
@BeforeSuite Once before entire suite Global (XML level)
@AfterSuite Once after entire suite Global (XML level)
@BeforeTest Once before a <test> block XML <test> tag
@AfterTest Once after a <test> block XML <test> tag
@BeforeClass Once before all methods in class Class-level
@AfterClass Once after all methods in class Class-level
@BeforeMethod Before each test method in a class Method-level
@AfterMethod After each test method in a class Method-level

📅 Interview Tip:

❓"What is the difference between @BeforeMethod and @BeforeTest?"

@BeforeTest @BeforeMethod
Runs once before all tests in <test> Runs before each test method
XML-level scope Java class-level scope

🚀 Summary

  • @BeforeSuite, @AfterSuite: suite-level setup/teardown
  • @BeforeTest, @AfterTest: test folder-level control
  • @BeforeClass, @AfterClass: class-wide setup/teardown
  • @BeforeMethod, @AfterMethod: per-method setup/cleanup
  • Groups: organize & execute selected test cases

🔮 Next Topic

Stay tuned for:

  • Data Providers: Parameterizing tests using @DataProvider
  • Parallel Execution & Prioritization
⚠️ **GitHub.com Fallback** ⚠️