Annotations

Annotations are metadata that provide additional information about code elements. In TestNG, annotations are used to define the behavior of test methods, classes, and suites. They enable you to perform setup, teardown, and other actions before and after test execution.
Annotations in TestNG are marked with the "@" symbol and are placed before a method or class. They help define the execution order, priority, data sources, and other attributes related to test cases.

Commonly Used TestNG Annotations

  • @Test: Marks a method as a test case.
  • @BeforeMethod: Run before each test method.
  • @AfterMethod: Run after each test method.
  • @BeforeTest: Run once before all the test methods in a tag.
  • @AfterTest: Run once after all the test methods in a tag.
  • @BeforeClass: Run once before all the test methods in a test class.
  • @AfterClass: Run once after all the test methods in a test class.
  • @BeforeSuite: Run once before the execution of all the test methods in the test suite.
  • @AfterSuite: Run once after the execution of all the test methods in the test suite.
  • @DataProvider: Supplies data to test methods for parameterization.
  • @Parameters: Passes parameters to test methods.
  • @Listeners: Listens to test events like test start and test failure.
  • @Factory: Creates instances of test classes for parallel execution.
Annotations allow you to configure your test environment by initializing resources, setting up connections, or loading data. For instance, you can use @BeforeMethod to open a browser before each test or @BeforeSuite to set up a database connection.
You can group test methods using annotations and define dependencies between test methods. This ensures a specific order of execution and allows you to skip certain tests if dependencies fail.