TestNG is a testing framework for Java, created by Cédric Beust. Its official site describes it as "inspired from JUnit and NUnit" and "designed to cover all categories of tests: unit, functional, end-to-end, integration". It is also the framework many Selenium suites are built on. Its current release is 7.12.0, published on 22 January 2026, and its README states that "TestNG requires Java 11 or higher".
This guide covers what you need to use TestNG well in 2027: setting it up with Maven, the annotation lifecycle, hard and soft assertions, groups, data providers, dependencies, parallel runs and retries. Every code sample below ran on 27 October 2026, on TestNG 7.12.0 with JDK 21 and Maven 3.9.16, and every output is copied from that run. Along the way we hit a change in Maven Surefire that will break many existing TestNG builds, so read the setup section even if you already use TestNG.
If you are writing your very first TestNG program, start with our step-by-step TestNG tutorial and come back here.
Why teams choose TestNG
TestNG covers every level of test automation, from unit tests to Functional testing and end-to-end suites. What sets it apart is control over how tests run, built into the framework rather than added through extensions:
- Grouping: tag tests as smoke, regression or anything else, and run one group.
- Data-driven tests: run one test method against many rows of data.
- Dependencies: skip tests automatically when a test they rely on fails.
- Parallel runs: run methods, classes or tests on several threads from one setting.
- Suite files: describe exactly what runs, and how, in an XML file.
These features are why TestNG is common in browser automation. A Selenium suite needs groups for smoke and regression runs, parallel threads to finish in reasonable time, and clear reports. Using TestNG in Selenium, you get all of them without building your own runner.
Setting up TestNG in 2027
Add TestNG with Maven
Most teams add TestNG through their build tool. This is the complete pom.xml we ran. It adds TestNG 7.12.0 and tells Maven Surefire, the plugin that runs tests, to use our suite file.
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>io.qable</groupId>
<artifactId>testng-guide</artifactId>
<version>1.0</version>
<properties>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.12.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.6</version>
<configuration>
<suiteXmlFiles><suiteXmlFile>testng.xml</suiteXmlFile></suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</project>The Surefire 3.6 change that breaks TestNG suite files
Our first run used the newest Surefire, 3.6.1, and failed before any test started:
Parameter "suiteXmlFiles" is not supported since 3.6.0:
TestNG tests now run on the JUnit Platform, which can't read TestNG suite XML files.
Remove it and select tests with "groups", "excludedGroups", "includes" or "excludes"
(or a JUnit Platform @Suite class),
or keep using maven-surefire-plugin 3.5.x.This is a deliberate change. Surefire's release notes for 3.6.0-M1 say it will "use junit platform runner to run junit 3, junit 4 and TestNG tests via vintage engine and testng engine". TestNG tests now run through the JUnit Platform, which cannot read testng.xml. If your build names a suite file, upgrading Surefire breaks it.
You have two ways forward:
- Stay on Surefire 3.5.x. We pinned 3.5.6, the latest 3.5 release, and every suite in this guide ran unchanged. This is the quickest fix.
- Move to the JUnit Platform route. Remove
suiteXmlFilesand select tests with Maven properties instead. On 3.6.1,mvn test -Dgroups=smokeran our one smoke test and-Dgroups=regressionran the five regression tests.
Two cautions if you choose the second route. Surefire 3.6.1's notes include a fix for "groups and excludedGroups being ignored when TestNG is on the classpath", so do not use 3.6.0 with groups. And in our 3.6.1 run, the listener declared in our testng.xml was not applied, because that file was no longer read. Check that your listeners and reports still work before you switch.
Installing TestNG in Eclipse

Eclipse needs the TestNG plugin to run tests from the editor:
- Open Help and choose Eclipse Marketplace.
- Search for "TestNG" and click Go.
- Click Install on TestNG for Eclipse.
- Confirm the selected features.
- Accept the licence and click Finish, then restart Eclipse.
TestNG in IntelliJ IDEA
IntelliJ IDEA supports TestNG out of the box. Its documentation notes that "IntelliJ IDEA comes bundled with TestNG 7.1.0", which is several releases old. Declare TestNG 7.12.0 in your build file, as above, so the IDE and your CI run the same version.
The annotation lifecycle
TestNG runs setup and clean-up methods around your tests, based on annotations. This class prints a line from each one:
package io.qable.shop;
import org.testng.annotations.*;
/** Shows the order in which TestNG runs configuration methods. */
public class LifecycleTest {
@BeforeSuite public void beforeSuite() { System.out.println("@BeforeSuite"); }
@BeforeTest public void beforeTest() { System.out.println("@BeforeTest"); }
@BeforeClass public void beforeClass() { System.out.println("@BeforeClass"); }
@BeforeMethod public void beforeMethod() { System.out.println(" @BeforeMethod"); }
@Test public void first() { System.out.println(" @Test first"); }
@Test public void second() { System.out.println(" @Test second"); }
@AfterMethod public void afterMethod() { System.out.println(" @AfterMethod"); }
@AfterClass public void afterClass() { System.out.println("@AfterClass"); }
@AfterTest public void afterTest() { System.out.println("@AfterTest"); }
@AfterSuite public void afterSuite() { System.out.println("@AfterSuite"); }
}And this is the order TestNG ran them in:
@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
@Test first
[PASS] LifecycleTest.first (9 ms, main)
@AfterMethod
@BeforeMethod
@Test second
[PASS] LifecycleTest.second (2 ms, main)
@AfterMethod
@AfterClass
@AfterTest
@AfterSuiteUse each level for the right job. Start a browser or database connection once per class in @BeforeClass when tests can share it. Reset state in @BeforeMethod when every test needs a clean start, such as a fresh browser session. Put suite-wide work, such as starting a test server, in @BeforeSuite.
Also read: What TestNG.xml is and how to use it
Writing tests: assertions, data and exceptions
The examples from here on test a small price calculator: it applies a discount code, then adds 8% tax, then rounds to two decimal places.
Data providers: one test, many rows
A data provider supplies rows of arguments, and TestNG runs the test once per row:
package io.qable.shop;
import static org.testng.Assert.assertEquals;
import java.math.BigDecimal;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class PriceCalculatorTest {
private PriceCalculator calc;
@BeforeMethod(alwaysRun = true)
public void setUp() {
calc = new PriceCalculator("0.08");
}
@Test(groups = "smoke")
public void totalAddsTaxWithNoDiscount() {
assertEquals(calc.total(new BigDecimal("100.00"), null), new BigDecimal("108.00"));
}
@DataProvider(name = "discounts")
public Object[][] discounts() {
return new Object[][] {
{"SAVE10", "100.00", "97.20"},
{"FLAT5", "100.00", "102.60"},
{"FLAT5", "3.00", "0.00"},
{"", "19.99", "21.59"},
};
}
@Test(groups = "regression", dataProvider = "discounts")
public void totalAppliesDiscountThenTax(String code, String items, String expected) {
assertEquals(calc.total(new BigDecimal(items), code), new BigDecimal(expected));
}
@Test(groups = "regression", expectedExceptions = IllegalArgumentException.class)
public void negativeItemTotalIsRejected() {
calc.total(new BigDecimal("-1.00"), null);
}
}TestNG reports each row as a separate result, with its parameters:
[PASS] PriceCalculatorTest.negativeItemTotalIsRejected (0 ms, main) <- IllegalArgumentException: item total cannot be negative
[PASS] PriceCalculatorTest.totalAddsTaxWithNoDiscount (0 ms, main)
[PASS] PriceCalculatorTest.totalAppliesDiscountThenTax [SAVE10, 100.00, 97.20] (2 ms, main)
[PASS] PriceCalculatorTest.totalAppliesDiscountThenTax [FLAT5, 100.00, 102.60] (2 ms, main)
[PASS] PriceCalculatorTest.totalAppliesDiscountThenTax [FLAT5, 3.00, 0.00] (0 ms, main)
[PASS] PriceCalculatorTest.totalAppliesDiscountThenTax [, 19.99, 21.59] (1 ms, main)The FLAT5 row with a 3.00 basket is the one that matters. A five-unit discount on a three-unit basket must not produce a negative total, and the row proves the calculator stops at zero. Edge cases like this belong in the data, where adding one costs a line.
The expectedExceptions attribute turns the error case into a passing test: the test passes only if the calculator rejects a negative basket. That is why its pass line shows the IllegalArgumentException: TestNG records the exception it expected.
Hard and soft assertions
A normal assertion stops the test at the first failure. TestNG's SoftAssert records every failure and reports them together when you call assertAll(). Here the same three checks on a receipt run both ways, with two wrong values on purpose:
package io.qable.shop;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
/** The same three checks on a receipt, as hard and as soft assertions. Two shown values are wrong on purpose. */
public class SoftAssertTest {
private final String shownItems = "40.98";
private final String shownTax = "3.10";
private final String shownTotal = "43.18";
@Test
public void hardAssertStopsAtFirstFailure() {
assertEquals(shownItems, "39.98", "item total");
assertEquals(shownTax, "3.20", "tax");
assertEquals(shownTotal, "43.18", "total");
}
@Test
public void softAssertReportsEveryFailure() {
SoftAssert soft = new SoftAssert();
soft.assertEquals(shownItems, "39.98", "item total");
soft.assertEquals(shownTax, "3.20", "tax");
soft.assertEquals(shownTotal, "43.18", "total");
soft.assertAll();
}
}[FAIL] SoftAssertTest.hardAssertStopsAtFirstFailure (8 ms, main) <- AssertionError: item total expected [39.98] but found [40.98]
[FAIL] SoftAssertTest.softAssertReportsEveryFailure (10 ms, main) <- AssertionError: The following asserts failed: item total expected [39.98] but found [40.98], tax expected [3.20] but found [3.10]The hard version reports only the item total; you would fix it, rerun and only then find the tax error. The soft version reports both at once. Use soft assertions when several independent values on one screen or response all need checking. Keep hard assertions when a later check makes no sense after an earlier one fails.
Organising a suite: groups and dependencies
Groups: run the smoke tests only
Groups let one codebase serve several runs. In the calculator test, one method is in the smoke group and the rest are in regression. This suite file runs only the smoke group:
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Smoke only">
<listeners>
<listener class-name="io.qable.shop.ResultPrinter"/>
</listeners>
<test name="smoke">
<groups>
<run>
<include name="smoke"/>
</run>
</groups>
<classes>
<class name="io.qable.shop.PriceCalculatorTest"/>
</classes>
</test>
</suite>[PASS] PriceCalculatorTest.totalAddsTaxWithNoDiscount (4 ms, main)
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.646 s -- in TestSuiteA typical pipeline runs the smoke group on every commit, because it takes seconds, and the full regression group before a release.
Dependencies: skip instead of fail
When one test needs another to have passed, say so with dependsOnMethods. If the first test fails, TestNG skips the dependent tests instead of running them into the same failure:
package io.qable.shop;
import org.testng.annotations.Test;
/** When login fails, the tests that need a logged-in user are skipped, not failed. */
public class DependencyTest {
@Test
public void login() {
throw new IllegalStateException("auth service returned 503");
}
@Test(dependsOnMethods = "login")
public void checkout() { }
@Test(dependsOnMethods = "login")
public void orderHistory() { }
@Test
public void productSearch() { }
}[FAIL] DependencyTest.login (0 ms, main) <- IllegalStateException: auth service returned 503
[PASS] DependencyTest.productSearch (1 ms, main)
[SKIP] DependencyTest.checkout (0 ms, main) <- Throwable: Method io.qable.shop.DependencyTest.checkout() depends on not successfully finished methods [io.qable.shop.DependencyTest.login()]
[SKIP] DependencyTest.orderHistory (0 ms, main) <- Throwable: Method io.qable.shop.DependencyTest.orderHistory() depends on not successfully finished methods [io.qable.shop.DependencyTest.login()](We removed TestNG's internal instance ids from the skip messages to keep the lines short.)
That gives you one failure with the real cause, plus two skips, instead of three failures that all say the same thing. productSearch does not depend on login, so it still ran and passed. Use dependencies sparingly, though: a long chain makes tests order-dependent and harder to run on their own.
Structuring a suite by test level
Groups work best when they follow a structure your whole team already understands. The ISTQB Certified Tester Foundation Level syllabus, version 4.0.1, gives one. It defines component testing, "also known as unit testing", as testing "components in isolation", and notes that it "often requires specific support, such as test harnesses or unit test frameworks". At the other end, system testing "focuses on the overall behavior and capabilities of an entire system or product, often including functional testing of end-to-end tasks".
TestNG can hold all of these levels in one codebase, which is part of its appeal. A practical layout looks like this:
- A group per level:
component,integrationandsystem, so a run can choose a level without anyone moving files. - A group per purpose:
smokefor the handful of checks that prove a build is worth testing,regressionfor everything that guards existing behaviour. - A test tag per environment or browser: a
<test>block per browser in testng.xml, so one suite file can run the same classes against Chrome and Firefox, or against staging and pre-production.
Then match the cadence to the cost. Component tests run in milliseconds, so run them on every commit. Smoke tests run on every deployment. The full system-level regression group runs before a release, in parallel. A test can belong to more than one group, so a system-level checkout test can also be in smoke.
Running faster: parallel tests
TestNG can run tests in parallel from the suite file, with no code changes. Our parallel test class has four methods that each wait one second, standing in for slow browser tests. This suite runs them on four threads:
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Parallel, 4 threads" parallel="methods" thread-count="4">
<listeners>
<listener class-name="io.qable.shop.ResultPrinter"/>
</listeners>
<test name="slow">
<classes>
<class name="io.qable.shop.ParallelTest"/>
</classes>
</test>
</suite>We ran the same four tests with thread-count="1" and with thread-count="4":
# thread-count="1"
[PASS] ParallelTest.a (1009 ms, TestNG-test-slow-1)
[PASS] ParallelTest.b (1002 ms, TestNG-test-slow-1)
[PASS] ParallelTest.c (1014 ms, TestNG-test-slow-1)
[PASS] ParallelTest.d (1003 ms, TestNG-test-slow-1)
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.681 s -- in TestSuite
# thread-count="4"
[PASS] ParallelTest.d (1009 ms, TestNG-test-slow-4)
[PASS] ParallelTest.b (1009 ms, TestNG-test-slow-2)
[PASS] ParallelTest.a (1020 ms, TestNG-test-slow-1)
[PASS] ParallelTest.c (1020 ms, TestNG-test-slow-3)
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.812 s -- in TestSuiteFour threads cut the run from 4.681 seconds to 1.812 seconds. The saving was not a full fourfold, because starting the suite has a fixed cost. Parallel runs only work if your tests do not share state: one browser per test and no shared static fields that tests write to. The parallel attribute also accepts classes, tests and instances, so you can keep tests that share a class on one thread.
Retrying flaky tests, and what retries hide
TestNG can retry a failed test through an IRetryAnalyzer. This one retries once:
package io.qable.shop;
import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;
/** Retries a failed test once. */
public class RetryOnce implements IRetryAnalyzer {
private int retries = 0;
@Override
public boolean retry(ITestResult result) {
return retries++ < 1;
}
}
package io.qable.shop;
import java.util.concurrent.atomic.AtomicInteger;
import org.testng.Assert;
import org.testng.annotations.Test;
/** A test that fails on its first attempt and passes on the second. */
public class RetryTest {
private static final AtomicInteger CALLS = new AtomicInteger();
@Test(retryAnalyzer = RetryOnce.class)
public void flakyStockCheck() {
int attempt = CALLS.incrementAndGet();
System.out.println(" flakyStockCheck attempt " + attempt);
Assert.assertTrue(attempt > 1, "stock service timed out");
}
} flakyStockCheck attempt 1
[SKIP] RetryTest.flakyStockCheck (0 ms, main) <- AssertionError: stock service timed out expected [true] but found [false]
flakyStockCheck attempt 2
[PASS] RetryTest.flakyStockCheck (0 ms, main)TestNG reports the failed first attempt as skipped and the second as passed, so the test ends green. Maven's two totals then disagree. The suite line counted the attempt and the summary line did not:
[ERROR] Tests run: 16, Failures: 3, Errors: 0, Skipped: 3, Time elapsed: 0.862 s <<< FAILURE! -- in TestSuite
[ERROR] Tests run: 15, Failures: 3, Errors: 0, Skipped: 2That is why retries need care. A test that only passes on its second attempt is telling you something: a race condition, a slow dependency or shared state. If your reports only show the final result, the warning disappears. Keep retries for causes outside your control, such as a test environment that is genuinely unstable, and track how often each test needs one.
TestNG's own changelog shows how tricky retries are. Release 7.12.0 fixed a case where "TestNG retry is going into infinite loop when the data provider returned object is modified before failure". If you combine retries with data providers, be on 7.12.0.
Reading TestNG's reports
Every run in this guide left the same set of reports in target/surefire-reports. Three of them earn their keep:
- index.html and emailable-report.html: browsable and email-friendly summaries of every suite, test and method, with the failure messages.
- testng-results.xml: the machine-readable result of the whole run, which CI tools and dashboards read.
- testng-failed.xml: a ready-made suite that reruns only what failed.
The last one is the most useful when a run goes red. TestNG's documentation says it "contains the necessary information to rerun only these methods that failed" and that it "will contain all the necessary dependent methods". Our file listed the two receipt tests that failed on purpose, the failed login, and both of the skipped tests that depend on it, so a rerun would rebuild the chain in order.
It did not list flakyStockCheck. That test failed once and passed on its retry, so as far as the rerun file is concerned, nothing went wrong. It is one more place where a retry removes the evidence of a flaky test.
Common mistakes in TestNG suites
These are the problems that most often make a TestNG suite slow, flaky or misleading. Each one follows from a feature covered above.
- Sharing state across parallel tests. A static WebDriver or a shared static field works on one thread and fails at random on four. Give each test its own browser and data.
- Using priority to force an order. The
priorityattribute schedules lower values first, but a suite that only passes in one order has hidden dependencies. Make each test set up what it needs, or declare the dependency withdependsOnMethods. - Long dependency chains. One early failure skips everything after it, which hides how much of the product actually works. Keep chains short.
- Retrying without tracking. As our run showed, a retried test ends green and drops out of
testng-failed.xml. Log every retry and review the tests that need them. - Hard assertions on screens with many values. You fix one wrong value per run. Use
SoftAssertwhere checks are independent. - Trusting the IDE's bundled TestNG. IntelliJ IDEA bundles TestNG 7.1.0. Declare the version in your build, so every machine runs the same one.
- Upgrading build plugins blindly. Surefire 3.6 stopped reading suite files, and 3.6.0 ignored groups. Pin plugin versions and upgrade them on purpose, with a test run.
TestNG and JUnit 5 compared
JUnit 5 is the main alternative on the JVM, and most TestNG features have a JUnit 5 counterpart. The difference is in how much is built in.
If your team already runs JUnit 5, there is little reason to move. If you need test dependencies, retries or suite files without adding extensions, TestNG still offers the most in one package.
Tools often listed as TestNG alternatives

Lists of "TestNG alternatives" usually show five tools. Only some of them do the same job.
- JUnit 5: a direct alternative on the JVM, compared above.
- NUnit: the equivalent framework for .NET languages, not for Java.
- Cucumber: a behaviour-driven development tool. It runs Gherkin scenarios and can run them on TestNG or JUnit, so it sits on top of a runner rather than replacing one.
- Selenium: automates browsers. It does not run or report tests, which is why it is so often paired with TestNG.
- Mockito: creates mock objects for unit tests, and works alongside TestNG or JUnit.
In short, choose between TestNG and JUnit 5, then add Selenium, Mockito or Cucumber to whichever you pick.
Final thoughts
TestNG remains a strong choice for Java test suites that need control over how tests run: groups for smoke and regression, data providers for edge cases, dependencies that skip cleanly and parallel runs from one setting. Use 7.12.0 on Java 11 or later, keep Surefire on 3.5.x while you rely on testng.xml, and treat every retry as a warning rather than a fix.
If you want help building or tidying a TestNG suite, QAble's automation testing services cover framework design, CI integration and the review of flaky tests.