In the previous section, we created a project and added TestNG to it. Our journey with the TestNG tutorial naturally starts with annotations, as they play a central role in structuring test cases.
What Are TestNG Annotations?
Annotations in TestNG are used to control the flow of test execution. They help define test methods and specify the order in which they should run. Each annotation begins with @ and is placed above the method it applies to.
Annotation |
Description |
@BeforeSuite |
Runs once before all tests in the entire suite. |
@AfterSuite |
Runs once after all tests in the entire suite are finished. |
@Test |
Marks a method as a test case. This is the core annotation used to define actual test steps |
@BeforeTest |
Runs before any test method that belongs to a class inside the |
@AfterTest |
Runs after all test methods belonging to the classes inside the |
@BeforeGroups |
Runs before the first test method in specified groups is invoked. |
@AfterGroups |
Runs after all test methods in the specified groups have been executed. |
@BeforeClass |
Runs once before the first test method in the current class. |
@AfterClass |
Runs once after all the test methods in the current class have run. |
@BeforeMethod |
Runs before each test method. |
@AfterMethod |
Runs after each test method. |
Java Program Using TestNG Annotations
Create a Java class inside TestNG Project, paste the following code into it, and run it to observe how each annotation works in the execution flow
Output
Workflow of Annotation
Annotations in TestNG follow a hierarchical structure, which helps control the execution flow of test cases. The standard execution order is:
@BeforeSuite → @BeforeTest → @BeforeClass → @BeforeMethod → @Test → @AfterMethod → @AfterClass → @AfterTest → @AfterSuite
@BeforeGroups and @AfterGroups are executed if we run the specified Groups. This topic is covered in the upcoming post.
Each annotation is triggered only once per its scope:
@BeforeSuite / @AfterSuite – run once for the entire test suite.
@BeforeTest / @AfterTest – run once per
@BeforeClass / @AfterClass – run once per class.
@BeforeMethod / @AfterMethod – run before and after each @Test method.
@Test – defines actual test logic.
@BeforeGroups / @AfterGroups – run before/after the first/last test method in the specified group.