Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 119 ยท Testing

Unit Testing with JUnit 6

Learn JUnit 6 step by step. Write @Test methods, use assertEquals, assertThrows and assertAll, name tests clearly and read pass and fail reports.

A unit test is a small piece of code that calls a piece of your program and checks that the answer is right. You write it once, and from then on it re-checks that behavior every time you build the project, in milliseconds, without a human clicking anything. When you later refactor a class, upgrade a library or fix a bug, the tests tell you right away whether you broke something.

JUnit is the standard testing framework for Java. Almost every Java project, from small libraries to Spring Boot services, uses it, and every IDE and build tool knows how to run it. This lesson covers JUnit 6, the current major version: how to add it to a project, how to write and run tests, the assertions you will use every day, and how to read a failure report. If you have never written a test before, the beginner lesson Unit Testing with JUnit is a gentler start.

What JUnit 6 is made of

JUnit is not one jar but a small family of modules:

  • JUnit Platform runs tests. Build tools (Maven, Gradle) and IDEs talk to the Platform's launcher, and the launcher asks test engines to discover and execute tests.
  • JUnit Jupiter is the engine and API you write tests with: @Test, Assertions, @BeforeEach and so on. Its packages start with org.junit.jupiter.
  • JUnit Vintage is an engine that runs old JUnit 3 and 4 tests. It is deprecated; new code uses Jupiter.

JUnit 6.0 shipped in September 2025. It needs Java 17 or newer, gives the Platform, Jupiter and Vintage one shared version number, and removes APIs that were deprecated during the JUnit 5 years. The everyday API did not change: tests written for JUnit 5 almost always compile and run unchanged on JUnit 6, so tutorials and Stack Overflow answers about "JUnit 5" still apply. Version 6.1 is current at the time of writing.

Adding JUnit to a project

With Maven, import the JUnit BOM (bill of materials) so every JUnit module gets the same version, then add the junit-jupiter aggregate with test scope. Maven's Surefire plugin finds and runs classes named *Test, Test* or *Tests during mvn test:

XML
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.junit</groupId>
      <artifactId>junit-bom</artifactId>
      <version>6.1.3</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>

With Gradle (Kotlin DSL), the same idea looks like this. useJUnitPlatform() tells Gradle's test task to use the JUnit Platform:

Kotlin
dependencies {
    testImplementation(platform("org.junit:junit-bom:6.1.3"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test {
    useJUnitPlatform()
}

Test code lives in src/test/java, in the same package as the class it tests, so it can reach package-private members. A test for src/main/java/com/shop/Discounts.java goes in src/test/java/com/shop/DiscountsTest.java. The Maven and Gradle lessons explain the build side in depth.

Your first test

Here is a tiny class that applies a percentage discount to a price in cents, and a test class for it. A test class is a plain class; each test is a method marked with @Test. Inside, you call the code and then assert what the result must be.

The examples on this page are complete programs. JUnit cannot be started by a build tool here, so each file ends with a short runTests(...) helper that calls the JUnit Platform launcher directly and prints one line per test. In a real project you never write that part: you run mvn test, gradle test or click the green arrow in your IDE. Focus on the test classes at the top.

Java A first JUnit test class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

All four lines start with [PASS], and the summary says 4 passed, 0 failed. A few rules about test classes and methods:

  • Test methods return void and must not be private or static. JUnit 6 skips such methods and logs a discovery warning such as "must not return a value. It will not be executed." Package-private (no modifier) is the usual style, and so is the test class itself in a real project.
  • JUnit creates a new instance of the test class for every test method. Fields are never shared between tests, so one test cannot leak state into another. The next lesson shows how to share setup on purpose.
  • Order is not guaranteed. JUnit runs methods in a fixed but deliberately non-obvious order (you may see them in a different order than in the source). Good tests never depend on each other.

The shape of a good test: Arrange, Act, Assert

Most tests have three parts, often separated by blank lines:

  1. Arrange: build the objects and inputs you need.
  2. Act: call the one method you are testing.
  3. Assert: check the result.
Java
@Test
void addingTwoItemsSumsTheirPrices() {
    var cart = new Cart();                 // Arrange
    cart.add(new Item("Pen", 150), 2);
    cart.add(new Item("Pad", 400), 1);

    long total = cart.totalCents();        // Act

    assertEquals(700, total);              // Assert
}

Keeping one "act" per test means a failing test points at exactly one behavior. When a test needs three different acts, it usually wants to be three tests.

Reading failures and errors

A test passes when its method returns normally. It fails when it throws. JUnit treats two kinds of throwing differently in reports, and knowing which one you are looking at speeds up debugging:

  • An assertion failure (AssertionFailedError) means the code ran but produced the wrong answer. The message shows expected and actual values.
  • Any other exception (a NullPointerException, StringIndexOutOfBoundsException, ...) means the code crashed before you could even check it. Many tools call this an error.

The next example tests a buggy initials method. Run it and read the three results.

Java Reading failure reports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

You get one pass and two failures, each telling a different story:

  • lowercaseNameGivesUppercaseInitials fails with AssertionFailedError: initials should be uppercase ==> expected: <AT> but was: <at>. The custom message comes first, then JUnit's own comparison. The code ran; the logic is wrong.
  • ignoresExtraSpaces fails with StringIndexOutOfBoundsException. Splitting " Grace Hopper " on single spaces produces empty strings, and charAt(0) on an empty string crashes. No assertion was ever reached.

Fix the method with fullName.strip().split("\\s+") and Character.toUpperCase(...), run again, and watch all three pass. That loop (see red, change code, see green) is the heart of testing, and the lesson on Test-Driven Development turns it into a discipline.

In a real project, the IDE shows the same information with a clickable stack trace, and Maven prints it under Failures: and Errors: at the end of mvn test, then fails the build.

The assertions you will use every day

All assertions are static methods of org.junit.jupiter.api.Assertions, which is why test files start with import static org.junit.jupiter.api.Assertions.*;. The most common ones:

Assertion Passes when
assertEquals(expected, actual) expected.equals(actual) (or == for primitives)
assertEquals(expected, actual, delta) two doubles/floats differ by at most delta
assertNotEquals(unexpected, actual) the values are not equal
assertTrue(condition) / assertFalse(condition) the boolean is true / false
assertNull(value) / assertNotNull(value) the reference is / is not null
assertSame(expected, actual) both references point to the same object
assertArrayEquals(expected, actual) arrays have equal length and elements
assertIterableEquals(expected, actual) two iterables yield equal elements in order
assertInstanceOf(Type.class, value) the value is a Type; returns it already cast
assertThrows(Type.class, executable) the code throws Type (or a subclass); returns the exception
assertDoesNotThrow(executable) the code finishes without throwing
assertAll(executables...) every grouped check passes; reports all failures together
assertTimeout(duration, executable) the code finishes within the time limit
fail(message) never: it fails the test immediately

Three details trip people up:

  • Expected comes first. assertEquals(1800, result), not assertEquals(result, 1800). Swapping them still passes and fails at the same times, but the failure message says "expected: " and sends you looking in the wrong direction.
  • Never compare floating-point results exactly. assertEquals(0.3, 0.1 + 0.2) fails with expected: <0.3> but was: <0.30000000000000004>. Pass a tolerance: assertEquals(0.3, 0.1 + 0.2, 1e-9). For money, use long cents or BigDecimal and the problem disappears (see BigInteger and BigDecimal).
  • Messages can be lazy. Every assertion takes an optional last argument: a String, or a Supplier<String> like () -> "user " + id that is only built when the assertion fails.

This example exercises most of the table on a small statistics helper. Every test passes; change a number in one of them to see its failure message.

Java Tour of the core assertions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

assertThrows returns the exception

Older JUnit code used @Test(expected = ...) or a try/catch with fail() inside. In Jupiter, assertThrows is the one way to do it, and because it returns the thrown exception, you can check its message or fields afterward, as emptyInputIsRejectedWithAClearMessage does. Two failure messages are worth recognizing:

  • Expected java.lang.IllegalStateException to be thrown, but nothing was thrown.
  • Unexpected exception type thrown, expected: <java.lang.IllegalStateException> but was: <java.lang.NumberFormatException>

assertThrows also accepts subclasses. When you need the exact type, use assertThrowsExactly.

Keep the lambda inside assertThrows to the single call that should throw. If setup code inside it throws the same exception type by accident, the test passes for the wrong reason.

assertAll reports every problem at once

Normally a test stops at the first failed assertion, so you fix one field, rerun, and discover the next. assertAll runs every check in the group and reports all failures together in a MultipleFailuresError. Compare the two tests below: both check the same wrong parser, but only the second shows you everything that is broken.

Java assertAll versus separate assertions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first test reports only expected: <Springfield> but was: <49007>. The second reports address (2 failures) and lists both wrong fields. Use assertAll when you check several properties of one result; do not use it to glue unrelated behaviors into one test.

Timeouts

assertTimeout(Duration.ofMillis(200), () -> service.load()) runs the code to completion and fails if it took too long, with a message like execution exceeded timeout of 10 ms by 40 ms. assertTimeoutPreemptively aborts the code when time runs out, but it runs it on another thread, which breaks code that relies on thread-local state (transactions, security contexts). Timing assertions are fragile on busy build servers, so give generous limits and keep them rare.

Naming tests

A test name is the first thing you read when it fails, often in a CI log at a bad moment. Make it say what behavior is expected, not which method is called:

  • Weak: test1(), testApply(), initialsTest().
  • Better: rejectsPercentAboveOneHundred(), ignoresExtraSpaces().
  • Also common: methodName_condition_expectedResult, such as apply_percentAbove100_throws().

Pick one style per project and stick to it. When a sentence reads better than camelCase, @DisplayName("rejects a discount above 100%") sets a human-friendly name; you will see it in the next lesson.

Common mistakes

  • Tests that cannot fail. A test with no assertion, or with an assertion that compares a value to itself, passes forever. Every new test should be seen failing at least once: break the code briefly and watch it go red.
  • Catching exceptions inside the test. try { ... } catch (Exception e) { } swallows the very failure you want to see. Let unexpected exceptions escape; add throws Exception to the test method if a checked exception is in the way.
  • Printing instead of asserting. System.out.println(result) needs a human to read it. An assertion checks it on every build.
  • Testing too much at once. One giant test that walks through a whole workflow tells you "something broke" but not what. Small tests pinpoint the problem.
  • Depending on time, randomness or test order. Pass the date, the random seed or the clock in as a parameter so the test controls it. Test Doubles and Mockito shows how.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A test calls assertEquals(result, 42) and result is 40. What does the failure message say?

    JUnit treats the first argument as the expected value. Swapping them still fails, but the message reports the values backward, which is why expected always goes first.
  2. 2. Which test method will JUnit 6 actually run?

    Test methods must return void and must not be private or static. JUnit 6 reports the other three as discovery warnings and does not execute them.
  3. 3. What happens when a test throws a NullPointerException before reaching any assertion?

    Any exception escaping a test method fails it. Reports show the actual exception type, which tells you the code crashed rather than returned a wrong value.
  4. 4. Why does assertEquals(0.3, 0.1 + 0.2) fail?

    Floating-point arithmetic is not exact. Use the overload with a tolerance, such as assertEquals(0.3, 0.1 + 0.2, 1e-9).
  5. 5. A test checks three fields with assertAll, and two of them are wrong. What is reported?

    assertAll executes every grouped assertion and collects all failures, so you see the whole picture in one run.

Summary

  • JUnit 6 = the Platform (runs tests) + Jupiter (the API you write against). It needs Java 17+, and JUnit 5 test code runs on it almost unchanged.
  • Add junit-jupiter with the junit-bom; put tests in src/test/java under the same package; run them with mvn test, gradle test or your IDE.
  • A test is a non-private, non-static void method marked @Test. JUnit makes a fresh instance of the class for each one and does not promise an order.
  • Structure tests as Arrange, Act, Assert, with one behavior per test and a name that describes it.
  • Know your assertions: assertEquals (expected first, delta for doubles), assertTrue, assertNull, assertArrayEquals, assertIterableEquals, assertThrows (returns the exception) and assertAll (reports every failure).
  • A failure means a wrong answer; any other exception means the code crashed. Watch every new test fail once so you know it can.

Next: Test Lifecycle and Organization, where you share setup code, group tests with @Nested, and skip or tag tests.