QA AND TEST AUTOMATION · PART 7 · BDD AND FRAMEWORK DESIGN · JAVA · 72 OF 112

TestNG vs JUnit 5: Listeners, Groups, Data Providers

The two Java test runners SDETs meet, side by side with ShopRung examples: lifecycle annotations, data providers versus parameterized tests, groups versus tags, testng.xml suites versus JUnit Platform suites, soft asserts versus assertAll, listeners versus extensions, dependencies between tests, parallel runs, and how to choose (or work in a codebase that already chose).

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Lifecycle
  • DataProvider vs ParameterizedTest
  • groups vs tags
  • XML suites
  • soft asserts
  • listeners vs extensions

Notes

Lifecycle

Both have setup and teardown at several levels. Before method and before each run around every test. Before class and before all run once per class. TestNG adds before suite and before test, tied to its XML suite file; JUnit five does that with extensions or suite classes. A key difference: TestNG creates one instance of the test class for all its methods, while JUnit five creates a new instance per test, which makes shared fields safer in JUnit.

Annotations side by side
TestNG              JUnit 5
@BeforeSuite        (extension)
@BeforeTest         (suite level)
@BeforeClass        @BeforeAll
@BeforeMethod       @BeforeEach
@AfterMethod        @AfterEach
@Test               @Test

TestNG: one instance per class
JUnit 5: new instance per test

Data-driven

Data driven tests look different but do the same job. TestNG uses a data provider method that returns rows of objects, and the test names it. JUnit five uses parameterized tests with sources: CSV source for inline rows, method source for a method that streams arguments, enum and value sources too. Here both check ShopRung's quantity limits: zero is four hundred, one is two hundred, eleven is four hundred.

Quantity boundaries, twice
// TestNG
@DataProvider Object[][] qty() {
  return new Object[][] {
    {0, 400}, {1, 200}, {11, 400}}; }
@Test(dataProvider = "qty")
void limits(int q, int status) {..}
// JUnit 5
@ParameterizedTest
@CsvSource({"0,400","1,200","11,400"})
void limits(int q, int status) {..}
// also @MethodSource, @EnumSource

Groups and tags

Both let you label tests and run a subset. TestNG has groups on the test annotation; JUnit five has tags. With Maven's Surefire plugin, dash D groups equals smoke works for both, and JUnit tag expressions allow combinations like smoke and not slow. Use this for quick smoke runs on every commit and the full suite nightly.

Smoke runs
// TestNG
@Test(groups = {"smoke", "cart"})
mvn test -Dgroups=smoke

// JUnit 5
@Tag("smoke") @Tag("cart")
mvn test -Dgroups=smoke
  (Surefire maps groups to tags)
  also: "smoke & !slow"

Suites

TestNG suites are usually described in an XML file: a suite with parallel settings, tests inside it, groups to include or exclude, and the classes or packages to run. Many legacy frameworks are driven entirely by testng dot xml files, one per environment or test type. JUnit five uses annotated suite classes and Maven configuration instead, which keeps everything in code.

testng.xml
<suite name="ShopRung"
       parallel="methods"
       thread-count="4">
  <test name="api">
    <groups><run>
      <include name="smoke"/>
    </run></groups>
    <packages><package
      name="dev.algorung.api"/>
  </packages></test>
</suite>

Assertions

Sometimes you want every check reported, not just the first failure. TestNG has soft assert: collect failures, then call assert all at the end; forget that call and the test silently passes, a classic bug. JUnit five has assert all with lambdas, which runs every check and reports all failures together. Watch the argument order too: TestNG's assert equals takes actual first, JUnit takes expected first.

Check several values
// TestNG
SoftAssert soft = new SoftAssert();
soft.assertEquals(cart.discount(), 500);
soft.assertEquals(cart.total(), 4999);
soft.assertAll();  // fails here

// JUnit 5
assertAll(
  () -> assertEquals(500, ...),
  () -> assertEquals(4999, ...));

Listeners and extensions

Both let you plug in code around tests. TestNG uses listeners, such as an I test listener with on test failure, registered with an annotation or in the XML. JUnit five uses extensions: a test watcher with test failed, or an after test execution callback as in the Selenium lab, registered with extend with or register extension. Typical uses: screenshots, logs, timing, retries and reporting.

Screenshot on failure
// TestNG
class Shots implements ITestListener {
  public void onTestFailure(
      ITestResult r) { save(...); } }
@Listeners(Shots.class)

// JUnit 5
class Shots implements
    TestWatcher { testFailed(...) }
@ExtendWith(Shots.class)
// or AfterTestExecutionCallback

Order and dependencies

TestNG supports dependencies between tests: cancel order depends on place order, and is skipped if it fails. JUnit five only offers an order annotation. Use these rarely. Tests that depend on each other cannot run alone or in parallel, as the flaky test lab showed. It is almost always better for each test to create what it needs, such as its own order through the API.

Dependencies
// TestNG
@Test void placeOrder() {...}
@Test(dependsOnMethods =
  "placeOrder")
void cancelOrder() {...}
// skipped if placeOrder fails

// JUnit 5: @Order + @TestMethodOrder
// better in both: each test makes
// its own order (flaky-test lab)

How to choose

How to choose. JUnit five is the default for new Java projects and is what Spring and modern tools expect, with extensions and nested tests. TestNG is in many existing Selenium frameworks, with XML suites, dependencies and rich listeners. Both run in parallel, both are data driven, both have groups or tags, Allure reports and CI support. In practice: learn both, and follow the codebase you join.

A fair summary
  • JUnit 5: default for new Java projects, Spring, Cucumber; extensions, @Nested, modern
  • TestNG: many existing Selenium frameworks; XML suites, dependencies, rich listeners
  • both: parallel, data-driven, groups/tags, Allure, CI → learn both; follow the repo

Common mistakes

Runner mistakes. Soft assert without assert all, so failures vanish. Actual and expected swapped, so messages mislead. A static web driver in TestNG parallel runs, where one instance serves many methods. Long chains of depends on methods. Mixing JUnit four, JUnit five and TestNG imports in one class, where some annotations are silently ignored. And XML suite files that nobody updates, so new tests never run.

Avoid these
  • SoftAssert without assertAll()
  • actual/expected swapped
  • static WebDriver in TestNG parallel runs
  • long dependsOnMethods chains
  • mixing JUnit 4, JUnit 5 and TestNG imports in one class
  • testng.xml nobody updates

Say it like this

In the interview: both are good. TestNG offers XML suites, groups, data providers, dependencies between tests and rich listeners, and is common in older Selenium frameworks. JUnit five creates a new instance per test and offers parameterized sources, tags, extensions and assert all, and is the default for new projects. I avoid test dependencies in both, keep tests independent for parallel runs, and follow what the repository already uses.

In the interview
  • "Both are good. TestNG: XML
  • suites, groups, data providers, dependencies, listeners; common
  • in older Selenium frameworks.
  • JUnit 5: new instance per test, parameterized sources, tags, extensions, assertAll; default
  • for new projects. I avoid test
  • dependencies in both and follow what the repo uses."

Interview questions

Q1What are the main differences between TestNG and JUnit 5?

TestNG: XML suites, groups, data providers, test dependencies, listeners, one instance per class. JUnit 5: new instance per test, parameterized sources, tags, extensions, assertAll, nested tests.

Q2How do you do data-driven testing in TestNG and JUnit 5?

TestNG: a @DataProvider method referenced by @Test(dataProvider=...). JUnit 5: @ParameterizedTest with @CsvSource, @MethodSource, @ValueSource or @EnumSource.

Q3What is a SoftAssert?

TestNG's collector of assertion failures that are reported together when assertAll() is called; forgetting assertAll() hides failures.

Q4What is testng.xml used for?

Defining suites and tests: which classes, packages or groups to run, parameters, listeners and parallel settings.

Q5What is the JUnit 5 equivalent of a TestNG listener?

An extension, such as TestWatcher or AfterTestExecutionCallback, registered with @ExtendWith or @RegisterExtension.

Q6How do you run only smoke tests?

TestNG groups or JUnit 5 tags, selected with -Dgroups=smoke in Maven Surefire (JUnit supports tag expressions).

Q7Should tests depend on each other?

Rarely: dependencies prevent running tests alone or in parallel; prefer each test creating its own data.

Q8Note on assertEquals argument order?

TestNG Assert.assertEquals(actual, expected); JUnit assertEquals(expected, actual). Swapping them gives misleading failure messages.