TestNG Annotations Execution Flow

Govindinee Attanagoda
Embla Tech
Published in
3 min readFeb 28, 2021
TestNG annotations

Before we proceed with TestNG Annotations Execution flow, let’s learn what TestNG annotations are.

TestNG annotation is a piece of code or data that has a special meaning for a Java method.

Let’s try to understand this using a simple example

When you commute between a suburb and a city, you will find few other places that you want to visit before you reach the city. Those places will be marked on your map as stops and you will pull the car over to get your things done at those stops.

TestNG annotations work the same. It will guide you the way you should go in the code. The code will be executed according to the annotations that you specify.

👉There are 3 types of TestNG annotations

Types of TestNG annotations

Our test automation scripts are very similar to manual test cases. With manual test cases also we usually have pre-conditions that we need to have. For example, in order to navigate to the homepage, we need to perform a login.

It is the same with automation. we have pre-conditions that must be set up before we test; then we have our test which is the condition; next is the post-condition that is performed after we complete our testing.

Let’s start with the highest level and add some print statements to demonstrate how the annotations can be used.

Let’s demonstrate by having annotations to login into an online booking system, schedule an appointment, and then logout from the application.

The annotations are displayed in order from lowest to highest.

On the console, we see the first few print statements in the following order:

This shows that the annotations have been executed in the following order:

  1. @BeforeSuite
  2. @BeforeTest
  3. @BeforeClass
  4. @BeforeMethod
  5. @Test
  6. @AfterMethod

The interesting part of this execution flow is @BeforeMethod always runs before the @Test method. In this case ‘Create an appointment’ which has a @Test annotation. And the @AfterMethod always runs after the @Test method. In this demo, the @AfterMethod prints “Logout”.

If we had an additional test for search an appointment, at this point we have finished creating an appointment. Chrome will be still set up, and the application remains open and we are not logged in. Now we start over with the @BeforeMethod, which is a precondition to search for an appointment.

🌟Let’s see how TestNG executes the pre-condition, the condition, and the post-condition based on our annotations

  1. @BeforeSuite
  2. @BeforeTest
  3. @BeforeClass
  4. @BeforeMethod
  5. @Test Create an appointment
  6. @AfterMethod
  7. @BeforeMethod
  8. @Test Search an appointment
  9. @AfterMethod
  10. @AfterClass
  11. @AfterTest
  12. @AfterSuite

This is how the code is executed based on our annotations.

Feel free to let me know your thoughts and comments on this. Be enlightened folks!🙂

--

--