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
- @BeforeClass
- @AfterClass
- @BeforeMethod
- @AfterMethod
- @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
See the execution order:
- First of all @BeforeClass is executed.
- Then @BeforeMethod
- @Test for f
- @AfterMethod
- @BeforeMethod
- @Test for g
- @AfterMethod
- @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
Feel free to ask queries or share your thoughts in comments or email us.
Comments
Post a Comment