TestNG Annotations

In this section we will discuss some of the important TestNG annotations frequently used.

@BeforeSuite

This method will be executed before any tests declared in the testng.xml file .

@BeforeTest

This method will be executed before <test> section in testng.xml

@AfterSuite

This method will be executed after all tests declared in the testng.xml file .

@AfterTest

This method will be executed after <test> section in testng.xml

 

Sample TestNG annotations code example:

package com.testingdocs.sample.testng;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.AfterSuite;

public class TestNGAnnotationsOrderExample {
    
  @Test
  public void sampleTest() {
      System.out.println("In Test Method");
  }
  
  @BeforeMethod
  public void beforeMethod() {
      System.out.println("In @BeforeMethod");
  }

  @AfterMethod
  public void afterMethod() {
      System.out.println("In @AfterMethod");
  }

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

  @AfterClass
  public void afterClass() {
      System.out.println("In @AfterClass");
  }

  @BeforeTest
  public void beforeTest() {
      System.out.println("In @BeforeTest");
  }

  @AfterTest
  public void afterTest() {
      System.out.println("In @AfterTest");
  }

  @BeforeSuite
  public void beforeSuite() {
      System.out.println("In @BeforeSuite");
  }

  @AfterSuite
  public void afterSuite() {
      System.out.println("In @AfterSuite");
  }

}

 

 

Run output of the program displays the order TestNG executes the annotated methods.

In @BeforeSuite
In @BeforeTest
In @BeforeClass
In @BeforeMethod
In Test Method
In @AfterMethod
In @AfterClass
In @AfterTest
PASSED: sampleTest

===============================================
Default test
Tests run: 1, Failures: 0, Skips: 0
===============================================

In @AfterSuite

===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

As you can see BeforeClass method is executed before the tests in the class. AfterClass is executed after all the tests in the class. Before/After method is executed before and after each test method execution.

Related Posts