TestNG Annotations

First, let's summarize the main annotations used in TestNG, which help in defining the execution order of the test methods:

  1. @BeforeSuite / @AfterSuite Methods under these annotations run before and after all tests in the suite, respectively.
  2. @BeforeTest / @AfterTest Executed before and after the <test> tags in the TestNG XML.
  3. @BeforeClass / @AfterClass Executed before the first method of the current class is invoked and after the last method in the current class executes.
  4. @BeforeMethod / @AfterMethod Executed before and after each test method.
  5. @BeforeGroups / @AfterGroups Run before and after the first and last test method that belongs to a group of tests.
  6. @Test Marks a method as a test method.


Execution Flow in TestNG

Understanding the sequence in which these annotations are triggered is crucial for setting up a proper test environment. Here is a typical flow of execution when using these annotations:

  1. @BeforeSuite Prepares the global test environment before any tests start.
  2. @BeforeTest Setup that needs to happen before each <test> block in the XML file.
  3. @BeforeClass Setup for the current test class, running once before any methods in the class.
  4. @BeforeGroups If the upcoming methods are part of a group, this runs before any methods in that group start.
  5. @BeforeMethod Runs immediately before each test method.
  6. @Test The test method itself is executed.
  7. @AfterMethod Cleanup that needs to occur after each test method.
  8. @AfterGroups After all methods in a group have executed, this cleans up group-specific settings.
  9. @AfterClass Cleanup after all methods in the current class have been executed.
  10. @AfterTest Runs after all classes and methods within a <test> block have finished execution.
  11. @AfterSuite Final cleanup after all tests across all test classes and groups have completed.

Diagrammatic Representation

A simple diagram illustrating the order of execution:

@BeforeSuite

@BeforeTest

@BeforeClass

@BeforeGroups

@BeforeMethod

@Test

@AfterMethod

@AfterGroups

@AfterClass

@AfterTest

@AfterSuite


Deepak Sharma

ISTQB Certified QA Lead/Project Manager at Cogniter Technologies

1y

Comprehensive article. Worth a read and then implement.

Like
Reply

To view or add a comment, sign in

Others also viewed

Explore topics