Annotations in TestNG

One of the key features that makes TestNG so powerful is its annotations. These annotations control the flow of test execution, making it easier to manage test cases, configurations, and the entire testing lifecycle. But before moving ahead to discuss them, we need to know what actually is an annotation.

An annotation is a tag representing metadata about classes, interfaces, variables, methods, or fields. An annotation does not change how the code functions; it simply provides additional instructions to either the Java compiler or during the program’s execution.

Below is the list of the TestNG annotations. This post will focus mainly on the @Before and @After annotations and their execution order. These annotations are needed to set up test data or perform cleanup activities for a test case. Questions about @Before and @After annotations are normally asked in the interview, especially about their execution order. Don’t worry; we’ll cover it all.

TestNG Annotations List
Annotation NameWhat does it do?
@BeforeSuiteThe annotated method will be run before all tests in this suite have run
@AfterSuiteThe annotated method will be run after all tests in this suite have run.
@BeforeTestThe annotated method will be run before any test method belonging to the classes inside the <test> tag is run.
@AfterTestThe annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.
@BeforeGroupsThe list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.
@AfterGroupsThe list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.
@BeforeClassThe annotated method will be run before the first test method in the current class is invoked.
@AfterClassThe annotated method will be run after all the test methods in the current class have been run.
@BeforeMethodThe annotated method will be run before each test method.
@AfterMethodThe annotated method will be run after each test method.
@DataProviderMarks a method as supplying data for a test method. The annotated method must return an Object[][] where each Object[] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.
@FactoryMarks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[].
@ListenersDefines listeners on a test class.
@ParametersDescribes how to pass parameters to a @Test method.
@TestMarks a class or a method as part of the test.

We have created separate articles for most annotations. If you want to learn more about any specific annotation, feel free to click for details and discover everything about it.

So, let’s talk about @Before and @After annotations.

Methods annotated with @Before annotations are executed before a test case/method is executed, whereas the methods annotated with @After annotations are executed after a test method is executed.

But, why would we need them?

@Before Annotations: These are used to set up preconditions required before executing a test, such as initializing resources or setting up configurations. They ensure that each test starts with a clean, predictable state.

@After Annotations: These handle post-test cleanup by releasing resources, closing connections, or resetting environments. They ensure that any changes made during the test are reversed, preventing interference with subsequent tests.

We now know why we need them, but there are so many @Before and @After annotations.

  • @BeforeSuite
  • @BeforeTest
  • @BeforeClass
  • @BeforeMethod
  • @AfterSuite
  • @AfterTest
  • @AfterClass
  • @AfterMethod

If we use all of them in a test suite, which would be executed first and which would be executed last?

Note: We haven’t mentioned @BeforeGroups and @AfterGroups, as they only come into the picture when we use groups in TestNG.

TestNG annotations order

Now, there are two ways to remember the hierarchy of @Before and @After annotations: one way is to cram it, and the other is to understand the reasons behind the hierarchy. We will go with the second one 😉

If you remember the testng.xml structure. It’s something like this

<suite name = "codekru">
    <test name = "codekrutest">
        <classes>
            <class name = "codekru.test1.CodekruTest1">
                <methods>
                    <include name = "test"/>
                </methods>
            </class>
        </classes>
    </test>
</suite>

Based on the above XML, you might be getting some hints on the execution order. Below file will further clarify the execution order.

<!--@BeforeSuite will execute here-->
<suite name = "codekru">
    <!--@BeforeTest will execute here-->
    <test name = "codekrutest">
        <classes>
            <!--@BeforeClass will execute here-->
            <class name = "codekru.test1.CodekruTest1">
                <methods>
                    <!--@BeforeMethod will execute here-->
                    <include name = "test"/> <!--@Test will execute here-->
                    <!--@AfterMethod will execute here-->
                </methods>
            </class>
            <!--@AfterClass will execute here-->
        </classes>
    </test>
    <!--@AfterTest will execute here-->
</suite>
<!--@AfterSuite will execute here-->

So, the execution order of @Before and @After annotation is –

  1. @BeforeSuite
  2. @BeforeTest
  3. @BeforeClass
  4. @BeforeMethod
  5. @Test
  6. @AfterMethod
  7. @AfterClass
  8. @AfterTest
  9. @AfterSuite

Below is a little example to demonstrate the above hierarchy –

package Test;

import org.testng.Assert;
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 CodekruTest {

	@BeforeSuite
	public void beforeSuiteMethod() {
		System.out.println("before Suite");
		Assert.assertTrue(true);
	}

	@BeforeTest
	public void beforeTestMethod() {
		System.out.println("before Test");
		Assert.assertTrue(true);
	}

	@BeforeClass
	public void beforeClassMethod() {
		System.out.println("before Class");
		Assert.assertTrue(true);
	}

	@BeforeMethod
	public void beforeMethod() {
		System.out.println("before Method");
		Assert.assertTrue(true);
	}

	@AfterSuite
	public void afterSuiteMethod() {
		System.out.println("after Suite");
		Assert.assertTrue(true);
	}

	@AfterTest
	public void afterTestMethod() {
		System.out.println("after Test");
		Assert.assertTrue(true);
	}

	@AfterClass
	public void afterClassMethod() {
		System.out.println("after Class");
		Assert.assertTrue(true);
	}

	@AfterMethod
	public void afterMethod() {
		System.out.println("after Method");
		Assert.assertTrue(true);
	}

	@Test()
	public void test() {
		System.out.println("Executing the test");
		Assert.assertTrue(true);
	}

}

Now, we will run the below testng.xml file and will see what happens and the order in which the output is printed

<suite name="codekru">
	<test name="codekru">
		<classes>
			<class name="Test.CodekruTest" />
		</classes>
	</test>
</suite>

Output –

before Suite
before Test
before Class
before Method
Executing the test
after Method
after Class
after Test
after Suite

===============================================
codekru
Total tests run: 1, Failures: 0, Skips: 0

Now, a few questions might pop up in your mind, but we will focus on one of the most interesting ones.

For example, if we place the @BeforeClass annotation on both the subclass and superclass, which method will execute first? The one annotated in the superclass or the one in the subclass?

In this case, TestNG guarantees that the @Before methods are executed in inheritance order (highest superclass first, then going down the inheritance chain), and the @After methods in reverse order (going up the inheritance chain).

This means that the @BeforeXXX annotated method in the superclass executes first, followed by the corresponding method in the subclass. Next, the @AfterXXX method of the subclass runs first, then the superclass’s @AfterXXX method.

Let’s try to see it with an actual example. Here, we have created two classes: CodekruTest and CodekruTestSubclass. CodekruTestSubclass extends the CodekruTest class.

superClass and subclass

CodekruTest.java

package Test;

import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;

public class CodekruTest {

	@BeforeClass
	public void beforeSuperClassMethod() {
		System.out.println("In before method of Superclass");
		Assert.assertTrue(true);
	}

	@AfterClass
	public void AfterSuperClassMethod() {
		System.out.println("In after method of Superclass");
		Assert.assertTrue(true);
	}

}

CodekruTestSubclass.java

package Test;

import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class CodekruTestSubclass extends CodekruTest {

	@BeforeClass
	public void beforeSubClassMethod() {
		System.out.println("In before method of Subclass");
		Assert.assertTrue(true);
	}

	@AfterClass
	public void AfterSubClassMethod() {
		System.out.println("In after method of Subclass");
		Assert.assertTrue(true);
	}

	@Test
	public void test() {
		System.out.println("Executing the test");
		Assert.assertTrue(true);
	}

}

and now, we will run the CodekruTestSubclass only and see what happens. Below is the testng.xml for that

<suite name="codekru">
	<test name="codekru">
		<classes>
			<class name="Test.CodekruTestSubclass" />
		</classes>
	</test>
</suite>

Output –

In before method of Superclass
In before method of Subclass
Executing the test
In after method of Subclass
In after method of Superclass

===============================================
codekru
Total tests run: 1, Failures: 0, Skips: 0
===============================================

Reference – https://testng.org/doc/

Video Tutorial

This is it. We hope that you liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.

Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *