Skip to content
VirtualLP Virtual Learning Platform

Unit Testing Frameworks: JUnit, TestNG and NUnit

14 min read Topic 7 of 31 4 hands-on labs

A unit test checks a small part of a program, usually one method. For example, a test can call add(2, 3) and check that the answer is 5.

A testing framework helps you write these checks, run them and read the results. This subject uses JUnit and TestNG (Test Next Generation) for Java, and NUnit for .NET.

Unit test

A unit test checks a small part of a program, often one method. A test framework helps you run many checks and read the results. JUnit, TestNG and NUnit are examples.

checking each bulb

Before decorating a house for Diwali, you test each bulb of the light string one by one. If one bulb is bad, you know exactly which one. Unit tests do this for each small piece of code.

Anatomy of a unit test – Arrange, Act, Assert

@Test
public void addReturnsSumOfTwoNumbers() {
    Calculator calc = new Calculator();      // Arrange
    int result = calc.add(2, 3);             // Act
    assertEquals(5, result);                 // Assert
}
  • Arrange – get things ready (create the calculator).
  • Act – do the one thing you are testing (add(2, 3)).
  • Assert – check the answer is what you expected (5).
Outcome Meaning
Pass All the assertions were true
Failure An expected result did not match; the program, test expectation or test data may be wrong
Error An unexpected exception happened – the test or the code crashed
Skipped / ignored The test was switched off (@Ignore, [Ignore], enabled = false)

The three frameworks compared

Feature JUnit 4 TestNG NUnit 3
Platform Java Java .NET (C#)
Test @Test @Test [Test]
Before / after each test @Before / @After @BeforeMethod / @AfterMethod [SetUp] / [TearDown]
Before / after all tests in the class @BeforeClass / @AfterClass (static) @BeforeClass / @AfterClass [OneTimeSetUp] / [OneTimeTearDown]
Expected exception @Test(expected = …) / assertThrows @Test(expectedExceptions = …) Assert.Throws<…>()
Parameterised tests @RunWith(Parameterized.class) @DataProvider [TestCase(…)]
Grouping / suites @Suite groups, testng.xml suites, dependsOnMethods, priority [Category]
Assertion order assertEquals(expected, actual) assertEquals(actual, expected) Assert.That(actual, Is.EqualTo(expected))
Argument order

JUnit's assertEquals takes (expected, actual), but TestNG's takes (actual, expected). Swapping them gives confusing failure messages.

Common assertions

Purpose JUnit / TestNG NUnit
Equality assertEquals Assert.That(x, Is.EqualTo(y)) / Assert.AreEqual
True / false assertTrue, assertFalse Is.True, Is.False
Null assertNull, assertNotNull Is.Null, Is.Not.Null
Decimal numbers assertEquals(0.3, x, 0.0001) Is.EqualTo(0.3).Within(0.0001)
Exceptions assertThrows(ArithmeticException.class, () -> …) Assert.Throws<DivideByZeroException>(() => …)
Why the "0.0001" for decimals?

Computers store decimals slightly inaccurately – 0.1 + 0.2 is really 0.30000000000000004. So we say "equal within a tiny tolerance", like accepting 299.99 g as "300 g" on a kitchen scale.

Lifecycle

sequenceDiagram
    participant R as Test runner
    participant C as Test class
    R->>C: @BeforeClass / [OneTimeSetUp]
    loop each @Test
        R->>C: @Before / @BeforeMethod / [SetUp]
        R->>C: test method
        R->>C: @After / @AfterMethod / [TearDown]
    end
    R->>C: @AfterClass / [OneTimeTearDown]

Writing good unit tests (FIRST)

Principle Meaning
Fast Runs in milliseconds
Independent No test depends on another test's result or order
Repeatable Same result every time, on any machine
Self-validating Pass/fail is decided by assertions, not by a person reading output
Timely Written with (or before) the code – as in TDD (Test-Driven Development)

Test positive cases (valid input), negative cases (invalid input, exceptions) and boundaries (0, maximum, empty).

Key point

Compare the three frameworks by annotations/attributes, lifecycle hooks, parameterised tests and suites. TestNG adds groups, priorities, dependencies and testng.xml.

Practise it

Virtual lab · Testing Tools · 30 min

JUnit tests for a web application’s search

Explore the VLP Demo Store, add Selenium and JUnit to an Eclipse project, run four search tests that drive Chrome, then break and fix an expectation using the failure trace.

Open lab

Virtual lab · Testing Tools · 35 min

Organise web tests with TestNG and testng.xml

Run a TestNG class with priorities, groups, a data provider and a dependency, convert it to a testng.xml suite, filter by groups and watch a dependent test get skipped.

Open lab

Virtual lab · Testing Tools · 30 min

Unit testing a Calculator with JUnit 4

Put JUnit 4 on the build path, run a real test class in Eclipse, watch the red bar on a wrong expectation, complete the division tests (delta comparison and expected exceptions) and add a parameterised test.

Open lab

Virtual lab · Testing Tools · 35 min

Unit-test an authentication class with NUnit in Visual Studio

Create a .NET 8 class library and an NUnit test project in Visual Studio 2022, wire the project reference, implement AuthService, and verify valid, invalid, empty-input and lock-out scenarios in Test Explorer and with dotnet test.

Open lab

Quick revision

  1. A unit test: Arrange → Act → Assert.
  2. Failure = assertion false; error = unexpected exception.
  3. Setup/teardown run around each test; class-level hooks run once.
  4. TestNG adds groups, priorities, dependencies and XML (Extensible Markup Language) suites.
  5. Cover positive, negative and boundary cases.

Practise this topic

Hands-on virtual labs

Apply what you just read in a realistic, guided simulation. Free with a verified account.

Create a free account to track your progress and unlock virtual labs.