Various annotations in TestNG

@BeforeSuite: This @BeforeSuite method will run before all the tests in the corresponding suite have run.
@AfterSuite: This @AfterSuite method will run after all the tests in the corresponding suite have run.
@BeforeTest: This @BeforeTest method will run before any test method belonging to the classes inside the  tag is run.
@AfterTest: This @AfterTest method will run after all the test methods belonging to the classes inside the tag have run.
@BeforeGroups: The list of groups that this configuration method will run before. This @BeforeGroups method is run before the first test method that belongs to any of these groups is invoked.
@AfterGroups: The list of groups that this configuration method will run after. This @AfterGroups method is run after the last test method that belongs to any of these groups is invoked.
@BeforeClass: This @BeforeClass method will be run before the first test method in the current class is invoked.
@AfterClass: This @AfterClass method will be run after all the test methods in the current class have been run.
@BeforeMethod: This @BeforeMethod method will be run before each test method.
@AfterMethod: This @AfterMethod method will be run after each test method.
@Test: The @Test method is a part of a test case.

Below is the annotation hierarchy in which the annotations are executed.

Let us see an example:

package testFramework;

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

public class TestCaseExecutionOrder {

  @Test
  public void test1() {
    System.out.println("This is test1: @Test");
  }

  @BeforeTest
  public void beforeTest() {
    System.out.println("This is beforeTest: @BeforeTest");
  }

  @AfterTest
  public void afterTest() {
    System.out.println("This is afterTest: @AfterTest");
  }

  @BeforeMethod
  public void beforeMethod() {
    System.out.println("This is beforeMethod: @BeforeMethod");
  }

  @AfterMethod
  public void afterMethod() {
    System.out.println("This is afterMethod: @AfterMethod");
  }

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

  @AfterClass
  public void afterClass() {
    System.out.println("This is afterClass: @AfterClass");
  }

  @BeforeSuite
  public void beforeSuite() {
    System.out.println("This is beforeSuite: @BeforeSuite");
  }

  @AfterSuite
  public void afterSuite() {
    System.out.println("This is afterSuite: @AfterSuite");
  }
}

 

Output: In this example we can see @suite executed at the first and last. Then @Test followed by @Class and similar for @Method annotation.