TestNG Annotations

TestNG uses annotations to help developers to write the tests.

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.

1. TestNG Test Annotations

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 listeners 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 method.

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.

  1. @BeforeSuite
  2. @BeforeTest
  3. @BeforeClass
  4. @BeforeMethod
  5. @Test
  6. @AfterMethod
  7. @AfterClass
  8. @AfterTest
  9. @AfterSuite

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.