TestNG Annotations

In this lesson, we will see some of the annotations that TestNG provides.

List of annotations #

TestNG supports annotations for performing various operations like:

  • @Test annotated method is considered as a test method. This annotation can be added at class level as well. When given at test method level, the one at method level will take precedence. A test method can be disabled by setting @Test(enabled = false). By default, enabled = true.

  • @BeforeSuite annotated method will run once per test suite before all the tests.

  • @AfterSuite annotated method will run once per test suite after all the tests.

  • @BeforeTest annotated method will run once per test before all the test methods.

  • @AfterTest annotated method will run once per test after all the test methods.

  • @BeforeClass annotated method will run once per every test class instance before all the test methods.

  • @AfterClass annotated method will run once per every test class instance after all the test methods.

  • @BeforeMethod annotated method will run once per every test method instance before all the test methods.

  • @AfterMethod annotated method will run once per every test method instance after all the test methods.

  • @BeforeGroup annotated method will run once per every test method instance before all the test methods that belong to the given group.

  • @AfterGroup annotated method will run once per every test method instance after all the test methods that belong to the given group.

  • @Parameter annotation on test method is to pass parameters to test methods.

  • @DataProvider annotated method is used to create test methods or test classes at runtime with different parameters. In conjunction with @Test on the test method, TestNG will create multiple test methods at runtime. It can also be added to the test class constructor in conjunction with @Factory to pass parameters to create test class instances at runtime.

  • @Factory can be used on a method that returns instances of test classes or on a test class constructor in conjunction with @DataProvider.

  • @Listeners is used at test class level to takes the array of classes that implements a plethora of implementations of ITestNGListener interface like IAlterSuiteListener, IAnnotationTransformer, IMethodInterceptor, IReporter, etc. for different purposes.

To know more about each of these annotations, please follow the link.

Sample TestNG class explaining the annotations #

Get hands-on with 1000+ tech skills courses.