JUnit 5 versus TestNG
JUnit 5 and TestNG run tests, wrap them in setup and teardown and report the result, while Selenium only controls the browser. One difference matters for UI: JUnit 5 creates a new class instance per method, while TestNG by default keeps one per class, so a driver field becomes shared in a parallel run. New projects most often choose JUnit Jupiter, now shipped as JUnit 6.
Selenium · Framework
A newcomer asks: "Why do we use TestNG rather than JUnit 5, and should we migrate?" What is the answer?
Selenium can control a browser, but it cannot run tests, prepare data or build a report: a test framework does that. Java has two common ones: JUnit 5 (Jupiter) and TestNG. In an existing project with four hundred tests the question "what do we use" is already settled, while in a new one it must be decided from scratch. The lesson covers how they differ in places that matter for UI automation (lifecycle, parameterisation, dependencies, parallelism) and by which signs they are chosen.
How it works and why. Both frameworks do one thing: find test methods, call them in a given order wrapped in setup and teardown, and report the result. The differences come down to how they model the lifecycle and what they treat as the norm. The most important difference for Selenium is the test class instance. JUnit 5 creates a new instance of the class for each test method (by default), so class fields are not shared between tests. TestNG by default keeps one instance per class, and a field holding the driver is shared between methods. When parallelism is turned on, in TestNG this turns into a race for one driver (details in the lesson “Parallel runs: a driver per thread, isolation, CI”).
| JUnit 5 | TestNG | |
|---|---|---|
| Setup and teardown | @BeforeEach, @AfterEach, @BeforeAll, @AfterAll (static unless PER_CLASS) | @BeforeMethod, @AfterMethod, @BeforeClass, @BeforeTest, @BeforeSuite |
| Parameterisation | @ParameterizedTest + @ValueSource, @CsvSource, @MethodSource | @DataProvider (can be parallel = true) |
| Grouping | @Tag + filters in the build | groups, testng.xml |
| Test dependencies | deliberately none: tests are independent | dependsOnMethods, dependsOnGroups |
| Extensions | Extension API (@ExtendWith, TestWatcher, ParameterResolver) | listeners (ITestListener, IRetryAnalyzer) |
| Parallelism | junit-platform.properties | parallel, thread-count in testng.xml |
| Class instance | a new one per method | one per class |
Example: the same test on both frameworks. Checking the home heading for two roles. First JUnit 5:
class RoleHomeTest {
private WebDriver driver;
@BeforeEach
void start() { driver = new ChromeDriver(); }
@AfterEach
void stop() { driver.quit(); }
@ParameterizedTest
@CsvSource({"admin,Admin panel", "guest,Welcome"})
void showsRoleHome(String role, String heading) {
driver.get(BASE + "/?as=" + role);
assertEquals(heading, driver.findElement(By.tagName("h1")).getText());
}
}
The same on TestNG:
public class RoleHomeTest {
private WebDriver driver;
@BeforeMethod
public void start() { driver = new ChromeDriver(); }
@AfterMethod(alwaysRun = true)
public void stop() { driver.quit(); }
@DataProvider(name = "roles")
public Object[][] roles() {
return new Object[][] {
{"admin", "Admin panel"}, {"guest", "Welcome"}};
}
@Test(dataProvider = "roles")
public void showsRoleHome(String role, String heading) {
driver.get(BASE + "/?as=" + role);
assertEquals(driver.findElement(By.tagName("h1")).getText(), heading);
}
}
The differences are visible at once. In TestNG the argument order of assertEquals is reversed (expected second), which is often mixed up when migrating. alwaysRun = true on the teardown is needed so that quit() runs even after a failure in a dependent chain or configuration. In TestNG the data set is a separate method with @DataProvider, while in JUnit 5 data sits right in the annotation. Both variants, however, do the main thing: the driver is created per test and closed after it.
Parallelism is turned on differently in each:
# src/test/resources/junit-platform.properties
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = concurrent
<suite name="ui" parallel="methods" thread-count="4">
<test name="ui-tests">
<classes><class name="tests.RoleHomeTest"/></classes>
</test>
</suite>
One class instance or a new one
A new instance
Each method has its own fields. A driver field is not shared between tests, so it is harder to end up in someone else's browser.
One instance
All methods of a class share fields. In a parallel run a driver field has to move into a ThreadLocal.
Limits and alternatives. New projects most often take JUnit Jupiter: a wider ecosystem, integration with IDEs, Maven/Gradle and CI, convenient extensions. The JUnit line has a newer version 6 that continues the same Jupiter model, so knowledge carries over. TestNG stays in big existing suites that already have groups, dependencies and testng.xml, and rewriting them without a reason is expensive. Dependencies between tests (dependsOnMethods) are handy for long scenarios but contradict the principle of independence: one failed test skips all the dependent ones, and parallelism becomes harder. JUnit 5 has no built-in retry: it is added with an extension or by rerunning failed tests at the Surefire or CI level, and a rerun should be marked as flaky (the lesson “Flaky tests: causes, diagnosis, artifacts and Allure”).
Every test must create its own state and not depend on order: this is the first condition of a parallel run in any framework, and it decides whether tests are stable better than the choice between JUnit and TestNG.
Common mistakes.
@BeforeAllwithoutstaticin JUnit 5 (withoutPER_CLASS): the test does not run because the method must be static.- Migrating a test to TestNG without swapping the
assertEqualsarguments: on failure the message mixes up expected and actual. - Building a scenario on
dependsOnMethodsand execution order: one failed step silently skips ten. - Mixing annotations of both frameworks in one project: some tests simply do not run.
Check yourself
TestNG tests with a WebDriver driver field in the class pass sequentially, but after parallel="methods" they fail randomly and click in someone else's window. Which framework difference is at work?
Answer
TestNG keeps one class instance for all methods, so the driver field is shared and parallel threads overwrite one reference. JUnit 5 by default creates a new instance for each method. The fix: a driver per thread (ThreadLocal) or a separate driver per method passed through a parameter.
Why is @BeforeAll in JUnit 5 usually unsuitable for creating a WebDriver if tests can run in parallel?
Answer
It runs once per class, so all tests share one browser and its state (cookies, open windows, the page). One driver cannot be shared safely between threads. The driver is created in @BeforeEach and closed in @AfterEach.
@BeforeEach and @ParameterizedTest, TestNG has @BeforeMethod and @DataProvider. Middle/Senior: For a new project I take JUnit 5 for the ecosystem and the Extension API, and keep TestNG where groups and dependencies already exist. I know the class instance differs (new per method in JUnit, one per class in TestNG), so before a parallel run I move the driver into a per-test fixture and do not build scenarios on dependencies between tests.