</>

Technology

TestNG

Difficulty

Intermediate

Interview Question

What are the important TestNG annotations in Selenium?

TestNG provides lifecycle annotations like @BeforeSuite, @BeforeTest, @BeforeClass, @BeforeMethod, @Test, and their @After counterparts.

Answer

TestNG annotations control the execution order of methods, from broadest scope (Suite) to narrowest (Method).

Execution order:

CODE
@BeforeSuite
  @BeforeTest
    @BeforeClass
      @BeforeMethod
        @Test
      @AfterMethod
    @AfterClass
  @AfterTest
@AfterSuite

Annotation reference:

AnnotationWhen it runs
@BeforeSuiteOnce before all test suites
@AfterSuiteOnce after all test suites
@BeforeTestBefore each test tag in testng.xml
@AfterTestAfter each test tag
@BeforeClassOnce before first method in the class
@AfterClassOnce after last method in the class
@BeforeMethodBefore each @Test method
@AfterMethodAfter each @Test method
@TestMarks a test method
@DataProviderSupplies data to @Test methods
@ParametersPasses parameters from testng.xml

Example:

Java
@BeforeClass
public void launchBrowser() { driver = new ChromeDriver(); }

@BeforeMethod
public void openURL() { driver.get("https://automateqa.online"); }

@Test
public void verifyTitle() { Assert.assertEquals(driver.getTitle(), "AutomateQA"); }

@AfterClass
public void closeBrowser() { driver.quit(); }

Follow AutomateQA

Related Topics