TestNG @AfterMethod Annotations (original) (raw)

Last Updated : 6 Aug, 2025

@AfterMethod is one of the TestNG Annotations. As the name defines, @AfterMethod is executed after each test method within a test class. Suppose there are n test methods within a test class, then n times @AfterMethod annotated method will be invoked. This annotation allows developers to specify various actions to be taken after test methods are run.

Let's understand the @AfterMethod annotation through an example.

**Step 1: In a Maven Project, create a TestNG Class that contains @AfterMethod.

**After_Method.java

Java `

package com.geeksforgeeks.test;

import org.testng.annotations.Test; import org.testng.annotations.AfterMethod;

public class After_Method {

@AfterMethod public void afterMethod() { System.out.println("This @AfterMethod will be executed after execution of each test method"); } @Test public void firstMethod() { System.out.println("This is firstMethod"); } @Test public void secondMethod(){ System.out.println("This is secondMethod"); } @Test public void thirdMethod() { System.out.println("This is thirdMethod"); } @Test public void fourthMethod() { System.out.println("This is fourthMethod"); } @Test public void fifthMethod() { System.out.println("This is fifthMethod"); } }

`

**Now, let's explain what this code does:

**afterMethod (@AfterMethod)

**Test Methods (@Test):

**Step 2: Now, we create the AnnotationsTest.xml file to configure the After_Method class.

XML `

    </classes>
</test>

`

**Step 3: Run the After_Method file. Right click on the After_Method and move the cursor down to Run As and then click on the TestNG Suite.

Output of AfterMethod Annotations

Output of AfterMethod Annotations

As we can observe in above code, the execution of different tests or methods is in proper order. First fifthMethod() Test is executed, then firsthMethod() test, after that secondMethod() and at the end thirdMethod() will be executed.