Skip to main content

TestNG cheatsheet

A one-page reference for TestNG. For listeners/reporting and interview Q&A, see the complete guide.

๐Ÿ“– Full guide: TestNG โ†’

Core annotationsโ€‹

@BeforeSuite  void suiteSetup() { ... }
@BeforeClass void classSetup() { ... }
@BeforeMethod void testSetup() { ... }

@Test(priority = 1)
void login() { ... }

@AfterMethod void teardown() { ... }

testng.xml suite configโ€‹

<suite name="Regression">
<test name="Smoke">
<classes>
<class name="tests.LoginTest"/>
</classes>
</test>
</suite>
mvn test -DsuiteXmlFile=testng.xml

Parallel executionโ€‹

<suite parallel="methods" thread-count="4">

parallel can be methods, classes, tests, or instances โ€” far more granular than JUnit 5's config-based parallelism.

Data-driven testingโ€‹

@DataProvider(name = "logins")
public Object[][] logins() {
return new Object[][] { {"admin", "right"}, {"admin", "wrong"} };
}

@Test(dataProvider = "logins")
void login(String user, String pass) { ... }

Groups & dependenciesโ€‹

@Test(groups = "smoke")
void quickCheck() { ... }

@Test(dependsOnMethods = "login")
void checkout() { ... }

Soft vs hard assertionsโ€‹

SoftAssert soft = new SoftAssert();
soft.assertEquals(actual1, expected1);
soft.assertEquals(actual2, expected2);
soft.assertAll(); // reports all failures together, not just the first

Listeners & reportingโ€‹

public class RetryListener implements ITestListener {
public void onTestFailure(ITestResult r) { captureScreenshot(); }
}
<listeners><listener class-name="RetryListener"/></listeners>

TestNG vs JUnit 5โ€‹

TestNGJUnit 5
Data-driven@DataProvider@ParameterizedTest
Parallelnative, granularconfig-based
DependenciesdependsOnMethodsnot built-in
See: TestNG vs. JUnit 5