How to use TestNG annotations and their execution flow


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 {
 
  @Test
  public void f() {
   System.out.println("f Test Case/Method");
  }
  
  @Test
  public void g() {
   System.out.println("g Test Case/Method");
  }
  
  @BeforeMethod
  public void beforeMethod() {
   System.out.println("Before Method");
  }

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

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

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

}


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

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
PASSED: f
PASSED: g

Do you get the execution order. If not let me make it clear:
  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! :)

For list of all TestNG (with Selenium Webdriver) posts click here: TestNG Posts

Subscribe to Facebook Group
Join Telegram channel of this website at https://t.me/techlisticspace
Feel free to ask queries or share your thoughts in comments or email me.

Comments

Popular posts from this blog

List of Selenium Demo Websites for Practice

How to learn Selenium Webdriver on your own online