Testng is a testing framework inspired by JUnit and NUnit, designed for test configuration flexibility and powerful reporting in Java. Annotations in TestNG control how and when test methods are executed.
TestNG annotations are special markers that you use to logically structure and control the execution flow of your tests. They tell the framework what a particular method is for and when it should be run relative to other tests, groups, classes, or the entire test suite.
Common Testng Annotations
| Annotation | Description |
|---|---|
| @BeforeSuite | Runs once before all tests in the suite |
| @AfterSuite | Runs once after all tests in the suite |
| @BeforeTest | Runs before <test> tag in TestNG XML file |
| @AfterTest | Runs after <test> tag in TestNG XML file |
| @BeforeClass | Runs before the first method in the current class |
| @AfterClass | Runs after all methods in the current class |
| @BeforeMethod | Runs before each @Test method |
| @AfterMethod | Runs after each @Test method |
| @Test | Marks a method as a test case |
| @DataProvider | Provides data for parameterized tests |
| @Parameters | Injects parameters from XML into test methods |
| @BeforeGroups | Runs before the first method of the specified group |
| @AfterGroups | Runs after the last method of the specified group |
Example java code of Testng Annotations:
Below is the TestNG test class contains all annotations as mentioned above. Statement will be printed on console on execution of particular annotation. @BeforeMethod and @AfterMethod will execute with each test associated with @Test.
Below in table order of annotations is also mentioned, that in which order annotations will be executed.
Suggested Posts:
1. First TestNG Script
2. TestNG Dependent Tests
3. TestNG Reports
4. Parameterization in TestNG
5. TestNG Reporter Log