How to use TestNG @After Annotation?

A TestNG class can have various @After TestNG methods. Such as: @AfterTest @AfterSuite @AfterClass @AfterMethod etc.

This article will explain the order of execution of different TestNG methods.

TestNG consists of following @After methods to support main @Test method. The order of execution of @After methods should be as following:


Key Points in this Order are

  • First of all, 1st @test() method is executed in above example.

  • The AfterSuite() method executes only once.

  • Even the methods AfterClass(), and AfterTest() methods are executed only once.

  • AfterMethod() method executes for each test case (every time for a new @Test) but after executing the test case.

Approach/Algorithm to Solve this Problem

  • Step 1: import org.testng.annotations.* for TestNG.

  • Step 2: Write an annotation as @test

  • Step 3: Create a method for the @test annotation as test1.

  • Step 4: Repeat the steps for test2 and test3.

  • Step 5: Write different annotations and their respective methods. Ex:, @AfterClass, @AfterMethod, @AfterSuite

  • Step 5: Now create the testNG.xml as given below.

  • Step 6: Now, run the testNG.xml or directly testNG class in IDE or compile and run it using command line.


The following code to show the order of different TestNG methods:

import org.testng.annotations.*;
import org.testng.annotations.Test;
public class OrderofTestExecutionInTestNG {
    // test case 1
    public void testCase1() {
        System.out.println("in test case 1");
    // test case 2
    public void testCase2() {
        System.out.println("in test case 2");
    public void afterMethod() {
        System.out.println("in afterMethod");
    public void afterClass() {
        System.out.println("in afterClass");
    public void afterTest() {
        System.out.println("in afterTest");
    public void afterSuite() {
        System.out.println("in afterSuite");


This is a configuration file that is used to organize and run the TestNG test cases.

It is very handy when limited tests are needed to execute rather than full suite.

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "" >

<suite name = "Suite1">
   <test name = "test1">
         <class name = "OrderofTestExecutionInTestNG"/>


in test case 1
in afterMethod
in test case 2
in afterMethod
in afterClass
in afterTest
in afterSuite

Updated on: 21-Aug-2023


Kickstart Your Career

Get certified by completing the course

Get Started