Annotations and Execution Order

A TestNG Class

package com.shopease.tests;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.*;

public class LoginTest {
    WebDriver driver;

    @BeforeClass  public void beforeClass() { System.out.println("BeforeClass"); }

    @BeforeMethod
    public void setUp() {
        driver = new ChromeDriver();
        driver.get("https://shopease.example.com/login");
    }

    @Test
    public void validLogin() {
        driver.findElement(By.id("email")).sendKeys("[email protected]");
        driver.findElement(By.id("password")).sendKeys("Test@123");
        driver.findElement(By.id("login-btn")).click();
        Assert.assertTrue(driver.getCurrentUrl().endsWith("/account"), "should land on /account");
    }

    @Test
    public void loginPageTitle() {
        Assert.assertEquals(driver.getTitle(), "Login - ShopEase");
    }

    @AfterMethod
    public void tearDown() { driver.quit(); }
}

Order of Annotations

@BeforeSuite        once per suite (whole testng.xml)
 @BeforeTest        once per <test> tag in testng.xml
  @BeforeClass      once per class
   @BeforeMethod    before EVERY @Test
    @Test
   @AfterMethod     after EVERY @Test
  @AfterClass
 @AfterTest
@AfterSuite

Example

This plain-Java simulation prints the order TestNG calls the methods for a class with two tests (TestNG runs test methods in alphabetical order by default):

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> tests = new ArrayList<>(List.of("validLogin", "loginPageTitle"));
        Collections.sort(tests);   // default TestNG order: by method name
        System.out.println("@BeforeSuite");
        System.out.println(" @BeforeClass");
        for (String t : tests) {
            System.out.println("  @BeforeMethod  -> open browser");
            System.out.println("   @Test " + t);
            System.out.println("  @AfterMethod   -> quit browser");
        }
        System.out.println(" @AfterClass");
        System.out.println("@AfterSuite");
    }
}

Output

@BeforeSuite
 @BeforeClass
  @BeforeMethod  -> open browser
   @Test loginPageTitle
  @AfterMethod   -> quit browser
  @BeforeMethod  -> open browser
   @Test validLogin
  @AfterMethod   -> quit browser
 @AfterClass
@AfterSuite

Running It

Example

Run the class with Maven:

mvn test -Dtest=LoginTest

Example output

[INFO] Running com.shopease.tests.LoginTest
BeforeClass
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 9.412 s - in com.shopease.tests.LoginTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS