</>

Technology

TestNG

Difficulty

Beginner

Interview Question

What are commonly used TestNG annotations?

TestNG annotations include @Test, @BeforeMethod, @AfterMethod, @BeforeClass, @AfterClass, @BeforeTest, @AfterTest, @BeforeSuite, and @AfterSuite.

Answer

Commonly Used TestNG Annotations

TestNG annotations define when a method should run relative to the test lifecycle.

Complete list of commonly used annotations:

Java
@Test              // Marks the method as a test case
@BeforeMethod      // Runs BEFORE each @Test method
@AfterMethod       // Runs AFTER each @Test method
@BeforeClass       // Runs BEFORE the first test in the class
@AfterClass        // Runs AFTER all tests in the class
@BeforeTest        // Runs BEFORE the first test tag in testng.xml
@AfterTest         // Runs AFTER all tests in the <test> tag
@BeforeSuite       // Runs BEFORE the entire test suite
@AfterSuite        // Runs AFTER the entire test suite

Execution order (lifecycle):

CODE
@BeforeSuite
  @BeforeTest
    @BeforeClass
      @BeforeMethod → @Test → @AfterMethod
      @BeforeMethod → @Test → @AfterMethod
    @AfterClass
  @AfterTest
@AfterSuite

Practical example:

Java
public class AnnotationDemo {

    @BeforeSuite
    public void beforeSuite() {
        System.out.println("Suite started — setup DB connection");
    }

    @BeforeClass
    public void beforeClass() {
        System.out.println("Class started — launch browser");
        driver = new ChromeDriver();
    }

    @BeforeMethod
    public void beforeMethod() {
        System.out.println("Before each test — navigate to home");
        driver.get("https://example.com");
    }

    @Test
    public void loginTest() {
        System.out.println("Running login test");
    }

    @Test
    public void searchTest() {
        System.out.println("Running search test");
    }

    @AfterMethod
    public void afterMethod() {
        System.out.println("After each test — clear cookies");
    }

    @AfterClass
    public void afterClass() {
        System.out.println("Class finished — close browser");
        driver.quit();
    }

    @AfterSuite
    public void afterSuite() {
        System.out.println("Suite finished — close DB connection");
    }
}

Common patterns:

  • @BeforeClass → Launch browser
  • @AfterClass → Quit browser
  • @BeforeMethod → Navigate to test page / clear state
  • @AfterMethod → Take screenshot on failure, logout

Follow AutomateQA

Related Topics