TestNG Annotations and their Execution Flow Explained

TestNG annotations are the most important part, they control the execution of test and other methods in the automation script. And in this post I am going to explain some of the important annoations. So, we will be covering following
  1. @BeforeClass
  2. @AfterClass
  3. @BeforeMethod
  4. @AfterMethod
  5. @Test
In below example, there are two methods f and g with @test annotation and every other annotation has one method each.

Code example:
package com.techlistic.selenium;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;

public class TestNGAnnotations {
  public void f() {
   System.out.println("f Test Case/Method");
  public void g() {
   System.out.println("g Test Case/Method");
  public void beforeMethod() {
   System.out.println("Before Method");

  public void afterMethod() {
   System.out.println("After Method");

  public void beforeClass() {
   System.out.println("Before Class");

  public void afterClass() {
   System.out.println("After Class");


Try to run this program on your setup and analyse the output. Below is the output.


[RemoteTestNG] detected TestNG version 6.14.3
Before Class
Before Method
f Test Case/Method
After Method
Before Method
g Test Case/Method
After Method
After Class

See the execution order:
  1. First of all @BeforeClass is executed.
  2. Then @BeforeMethod
  3. @Test for f
  4. @AfterMethod
  5. @BeforeMethod
  6. @Test for g
  7. @AfterMethod
  8. @AfterClass
Now, you would be able to make out the execution flow. So, this way you can create your setup, teardown methods and use whatever before/after annotation with it as per your requirement. If you want to execute your setup only once at class level then use @BeforeClass or if you want to execute setup before every test case/method then use @BeforeMethod (Same for teardown). Happy Learning! :)

Install TestNG  << Previous    ||    Next >>  Selenium-TestNG Integration

Follow Us

Quora Space | Facebook Page | Telegram Channel
Feel free to ask queries or share your thoughts in comments or email us.


Popular posts from this blog

10 Best Demo Websites for Automation Testing Practice

Automate 'User Registration' of E-commerce Website using Selenium

Automate E-Commerce Website using Selenium Webdriver

Automate Browser Actions on Godaddy.com using Selenium