Back to cheat sheet hub

TestNG Cheat Sheet

A compact TestNG reference for building maintainable Selenium suites with the right annotations, data flow, and execution controls.

Selenium Module 6 Annotations Parallel execution

Core Annotations

Lifecycle annotations help define setup and cleanup at the right scope.

@BeforeSuite
@BeforeClass
@BeforeMethod
@Test
@AfterMethod
@AfterClass

Simple Test

Keep tests focused and independent.

@Test
public void validLoginShouldWork() {
    Assert.assertTrue(true);
}

Priority and Groups

Use these for organization, not as a replacement for strong test independence.

@Test(priority = 1, groups = {"smoke", "login"})
public void loginTest() {}

dependsOnMethods

Use cautiously. Strong suites usually avoid chaining tests together.

@Test
public void createAccount() {}

@Test(dependsOnMethods = "createAccount")
public void verifyAccount() {}

Assertions

TestNG assertions are direct and useful for core validation work.

Assert.assertEquals(actual, expected);
Assert.assertTrue(condition);
Assert.assertNotNull(object);

Soft Assertions

Soft assertions let multiple checks run before failing together.

SoftAssert soft = new SoftAssert();
soft.assertTrue(true);
soft.assertEquals("A", "A");
soft.assertAll();

DataProvider

Use DataProviders for simple data-driven test coverage.

@DataProvider
public Object[][] loginData() {
    return new Object[][] {
        {"user1", "pass1"},
        {"user2", "pass2"}
    };
}

testng.xml

XML suites help organize execution, parallelization, and parameters.

<suite name="Regression">
  <test name="Login Tests">
    <classes>
      <class name="tests.LoginTest"/>
    </classes>
  </test>
</suite>

Listeners and Retries

Use listeners for reporting and retries for controlled flaky behavior only.

public class Retry implements IRetryAnalyzer {
    public boolean retry(ITestResult result) {
        return false;
    }
}

Parallel Execution

Parallel runs speed up suites, but only if setup and data are isolated.

<suite parallel="tests" thread-count="3">