Execution Sequence of Annotations in TestNG

In the previous post, we have seen how to execute a set of test cases using Test Suite. In this post, we will learn about the sequence of annotations.

Till now, we have seen the working of @AfterMethod,@BeforeMethod and @Test. Apart from these ,there are so many other annotations as well. There might be some scenarios where you may have to use all or might be during automation framework development.

So, it is important to understand the sequence in which all annotations will be executed. Let’s understand with a pictorial presentation first as given below, then we will understand how to use them in a program.

Execution Sequence of Annotations in TestNG:

Execution sequence of annotations in TestNG

 

Example of annotations sequence: 

package com.testsuite.example;

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 AnnotationsExample {

			@Test

			public void testCase1() {

				System.out.println("This is the Test Case 1");

			}

			@Test

			public void testCase2() {

				System.out.println("This is the Test Case 2");

			}

			@BeforeMethod

			public void beforeMethod() {

				System.out.println("This will execute before every Method");

			}

			@AfterMethod

			public void afterMethod() {

				System.out.println("This will execute after every Method");

			}

			@BeforeClass

			public void beforeClass() {

				System.out.println("This will execute before the Class");

			}

			@AfterClass

			public void afterClass() {

				System.out.println("This will execute after the Class");

			}

			@BeforeTest

			public void beforeTest() {

				System.out.println("This will execute before the Test");

			}

			@AfterTest

			public void afterTest() {

				System.out.println("This will execute after the Test");

			}

			@BeforeSuite

			public void beforeSuite() {

				System.out.println("This will execute before the Test Suite");

			}

			@AfterSuite

			public void afterSuite() {

				System.out.println("This will execute after the Test Suite");

			}

}

Output: 

Annotations execution in TestNG


Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum

 

Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. pavan says:

    Nice work