TestNG uses annotations to help developers to write the tests. Let us learn a few important testng annotations and their lifecycle.
1. TestNG Annotations
The following is a table containing information about all the annotations provided by TestNG and a brief description of them. The source code of all the annotations can be found in the Git repository.
Annotation | Description |
---|---|
@BeforeSuite | The annotated method will be executed before any tests are declared inside a TestNG suite. |
@AfterSuite | The annotated method will be executed after any tests are declared inside a TestNG suite. |
@BeforeTest | The annotated methods will be executed before each test section is declared inside a TestNG suite. |
@AfterTest | The annotated methods will be executed after each test section is declared inside a TestNG suite. |
@BeforeGroups | BeforeGroups annotated method will run before any of the test methods of the specified group is executed. |
@AfterGroups | AfterGroups annotated method will run after any of the test methods of the specified group gets executed. |
@BeforeClass | BeforeClass annotated method is executed before any of the test methods of a test class. |
@AfterClass | AfterClass annotated method is executed after the execution of every test method of a test class are executed. |
@BeforeMethod | These annotated methods are executed before the execution of each test method. |
@AfterMethod | These annotated methods are executed after the execution of each test method. |
@DataProvider | Marks a method as a data-providing method for a test method. The said method has to return an Object double array (Object[ ][ ]) as data. |
@Factory | Marks an annotated method as a factory that returns an array of class objects (Object[ ]). These class objects will then be used as test classes by TestNG. This is used to run a set of test cases with different values. |
@Listeners | Applied on a test class. Defines an array of test listener classes extending org.testng.ITestNGListener. Helps in tracking the execution status and logging purpose. |
@Parameters | This annotation is used to pass parameters to a test method. These parameter values are provided using the testng.xml configuration file at runtime. |
@Test | Marks a class or a method as a test method. If used at the class level, all the public methods of a class will be considered as a test methods even if they are not annotated. |
Refer to this table of TestNG Annotations whenever you are in confusion.
2. Test Lifecycle
Let us see the sequence in which the methods annotated with the above annotations get executed.
- @BeforeSuite
- @BeforeTest
- @BeforeClass
- @BeforeMethod
- @Test
- @AfterMethod
- @AfterClass
- @AfterTest
- @AfterSuite
Happy Learning !!