Skip to content
Tutorials Center
My learning

Topics

Lesson 161 of 201 ยท JVM and Advanced Topics

Unit Testing with JUnit

Learn unit testing in Java with JUnit - why tests matter, @Test methods, assertions, the Arrange-Act-Assert pattern, reading failures and writing good tests.

How do you know your code works? Most beginners run the program, look at the output and decide it "looks right." That works for one small program, once. It stops working when the program grows, when you change something six weeks later, or when a teammate edits a method you depend on. Nobody re-checks every feature by hand after every change.

A unit test is a small program that checks one piece of your code, usually a single method or class, and reports automatically whether it behaves as expected. You write it once, and then it re-checks that behavior in milliseconds every time you build. Tests catch regressions the moment you introduce them, document how code is supposed to be used, and give you the confidence to clean up code without fear. In Java, the standard tool for this is JUnit.

This lesson is a gentle introduction: you'll write tests by hand first to see the idea, then switch to JUnit, learn the essential assertions, read failure reports, and pick up the habits that make tests useful. The Advanced Java track goes much deeper.

Testing by hand, without a framework

Here's a small method that's easy to get subtly wrong, and a main method that checks it against answers worked out on paper:

Java Checking a method by hand

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 third check fails: the comment says "free from 5000," but the code uses > instead of >=. This is the most common kind of bug in real code, an off-by-one at a boundary, and a test found it before any customer did. Change > to >= and run again: all four checks pass.

The idea works, but hand-made checks have limits. Nothing stops the program at the first exception, so one crash hides every later result. There's no standard way to check exceptions, no nice failure messages, and no way for your build tool or IDE to find and run all checks in a project. That's what a testing framework provides.

JUnit in a nutshell

JUnit is used by almost every Java project. The current major version, JUnit 6 (released in 2025, requiring Java 17+), has two parts you'll hear about:

  • JUnit Jupiter: the API you write tests with (@Test, assertEquals, ...), in the package org.junit.jupiter.api.
  • The JUnit Platform: the engine that discovers and runs tests. Maven, Gradle and every major IDE talk to it.

In a real project, you add JUnit as a test dependency with your build tool, put tests under src/test/java in the same package as the class under test, and run them with one command:

XML
<!-- Maven: pom.xml -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>6.0.0</version>
    <scope>test</scope>
</dependency>
TEXT
src/main/java/com/shop/Shipping.java        โ† the code
src/test/java/com/shop/ShippingTest.java    โ† its tests

mvn test          (Maven)
./gradlew test    (Gradle)

Our editor has the JUnit Platform on its classpath, so you can run real JUnit tests here. Each example puts the test class inside Main as a public static nested class, and a short runTests helper at the bottom asks the JUnit Platform's launcher to run it and print the results. You don't need to understand the helper; in a project, Maven, Gradle or your IDE does that job.

Your first JUnit test

A test is a method annotated with @Test. Inside, you call the code and assert what the result should be. If every assertion holds, the test passes. If one fails, JUnit stops that test, records the failure with a clear message, and moves on to the next test.

Java Your first JUnit tests

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 tests pass. Some things to notice:

  • assertEquals(expected, actual): the expected value comes first. Swapping them still detects bugs, but the failure message then says "expected" for the wrong value, which confuses whoever reads it.
  • assertThrows(Type.class, () -> ...) passes only if the lambda throws that exception type (or a subclass). If the code doesn't throw, the test fails.
  • import static org.junit.jupiter.api.Assertions.*; is a static import, so you can write assertEquals instead of Assertions.assertEquals.
  • Test methods are not private, not static, and return void. Package-private (no modifier) is the usual style. JUnit creates a new instance of the test class for every test method, so tests can't leak state into each other through fields.
  • The test names are full sentences. When a test fails in a report of 2,000 tests, orderOfExactlyFiftyShipsFree tells you what broke without opening the file.
  • The order in which JUnit runs test methods is deliberately not the source order. Good tests never depend on each other.

The Arrange, Act, Assert pattern

Most tests have the same three-part shape, often separated by blank lines:

  1. Arrange: create the objects and data the test needs.
  2. Act: call the one method you're testing.
  3. Assert: check the result (and only what this test is about).
Java
@Test
void addingTheSameItemTwiceIncreasesQuantity() {
    // Arrange
    Cart cart = new Cart();
    cart.add("tea", 1);

    // Act
    cart.add("tea", 2);

    // Assert
    assertEquals(3, cart.quantityOf("tea"));
}

If the Arrange part gets long, that's a hint the code under test has too many dependencies, which the design principles lesson helps with (dependency inversion makes classes easy to set up in tests). If the Act part has several calls, you may be testing several behaviors at once; split the test.

Reading a failing test

Tests are only useful if their failures are easy to understand. Here's a Cart class with two bugs. Run the tests and read the report:

Java What failures look like

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 report shows two different kinds of problems:

  • A failed assertion (AssertionFailedError): the code ran, but the answer was wrong. The message quantity of tea ==> expected: <3> but was: <2> says exactly what happened: the optional message you passed, the expected value and the actual one. A value of 2 instead of 3 points straight at put replacing the old quantity.
  • An unexpected exception (here a NullPointerException): the code crashed before any assertion could run. Thanks to helpful NullPointerException messages, it even explains that unboxing a null Integer failed.

One failing test didn't stop the others: newCartIsEmpty still ran and passed. Now fix the class: use quantities.merge(item, quantity, Integer::sum) in add and quantities.getOrDefault(item, 0) in quantityOf, then rerun until everything is green. This loop (see a red test, fix the code, see green) is the everyday rhythm of testing, and Test-Driven Development turns it into a design technique.

The assertions you'll use most

All of these are static methods of org.junit.jupiter.api.Assertions. Each accepts an optional last argument: a message, or a Supplier<String> that builds the message only when the assertion fails.

Assertion Passes when
assertEquals(expected, actual) The values are equal (uses equals for objects)
assertEquals(expected, actual, delta) Two doubles differ by at most delta
assertNotEquals(a, b) They're not equal
assertTrue(condition) / assertFalse(condition) The condition is true / false
assertNull(x) / assertNotNull(x) x is / isn't null
assertSame(a, b) a and b are the same object (==)
assertArrayEquals(a, b) Two arrays have equal elements in the same order
assertIterableEquals(a, b) Two iterables (like lists) have equal elements in order
assertThrows(Type.class, executable) The code throws that exception type; returns the exception
assertDoesNotThrow(executable) The code throws nothing
assertAll(executables...) Runs every check and reports all failures together
fail(message) Never: fails the test immediately
Java The everyday assertions in action

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 last test fails on purpose to show assertAll: instead of stopping at the first wrong value, it runs all three checks and lists both failures in one report (98.6 ยฐF is the right answer, and 37 ยฐC is of course not freezing). Two more lessons from this example:

  • Never compare doubles exactly. 36.6 * 9 / 5 + 32 isn't exactly 97.88 in binary floating point (see Working with Numbers), so pass a tolerance as the third argument.
  • assertThrows returns the exception, so you can check its message too.

What makes a good unit test

A widely used checklist is FIRST. Good unit tests are:

  • Fast: milliseconds each, so you run thousands of them all the time. Avoid real networks, databases, files and Thread.sleep in unit tests.
  • Independent: each test sets up its own data and works in any order.
  • Repeatable: the same result every run, on every machine. Inject a fixed Clock or a seeded Random instead of using the current time or true randomness.
  • Self-validating: pass or fail automatically; nobody reads printed output.
  • Timely: written together with the code (or before it), not "someday."

Some more habits that pay off:

  • Test behavior, not implementation. Assert on what a method returns or what a caller can observe, not on private fields or the exact sequence of internal calls. Then you can refactor the inside freely.
  • One behavior per test, with a descriptive name. Several assertions are fine when they check one behavior.
  • Hunt the edges. Bugs live at boundaries: empty strings and collections, 0, 1 and negative numbers, the exact threshold value (like 5000 above), null, very large values, duplicates.
  • Write a failing test before fixing a bug. It proves you understood the bug and keeps it from ever coming back.
  • Keep tests simple. A test with loops and ifs needs its own tests. Prefer plain, repetitive, obvious code.

Let's apply these habits to a slightly bigger example: a password policy with several rules. Each test checks one rule, the names read like a specification, and the edge cases (exactly 12 characters, 11 characters) are covered explicitly:

Java Testing a password policy

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.

@BeforeEach marks a setup method that JUnit runs before every test, so each test starts with a fresh object. Try breaking the policy on purpose (change < to <= in the length check, or remove toLowerCase()) and watch exactly which tests fail; that's a quick way to check that your tests really protect the behavior they claim to.

Where to go next

You now know enough to test your own classes. Real projects add more tools, all covered in the Advanced Java track:

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A test runs assertEquals(500, calculator.total()); and total() returns 450. What does the failure message say?

    assertEquals takes the expected value first and the actual value second, and its message reports them in that order.
  2. 2. What happens with assertThrows(IllegalArgumentException.class, () -> parseAge("42")) if parseAge returns 42 normally?

    assertThrows passes only when the code throws the given exception type (or a subtype). Returning normally is a failure.
  3. 3. Why does assertEquals(0.3, 0.1 + 0.2) fail, and what should you write?

    Binary floating point can't represent 0.1 and 0.2 exactly, so compare doubles with a tolerance (delta) as the third argument.
  4. 4. Two tests in the same class both modify a field initialized in the test class. Can one test's changes affect the other?

    By default JUnit uses a fresh instance per test method, so instance fields start over for every test. Static fields, however, are shared, so avoid mutable static state in tests.
  5. 5. Which is the best example of a boundary test for "orders of 5000 cents or more ship free"?

    Bugs cluster at thresholds, so test the values right at and next to the boundary. Random inputs also break repeatability.

Summary

  • A unit test automatically checks one small piece of code; tests catch regressions instantly and make refactoring safe.
  • JUnit 6 = the Jupiter API (@Test, assertions) + the Platform that build tools and IDEs use to run tests. Tests live in src/test/java and run with mvn test or gradle test.
  • Test methods are non-private, non-static void methods annotated with @Test; JUnit creates a fresh instance per test and doesn't guarantee order.
  • Structure tests as Arrange, Act, Assert. Use assertEquals(expected, actual) (with a delta for doubles), assertTrue/assertFalse, assertThrows and assertAll.
  • A failure shows the expected and actual values; an unexpected exception shows the crash. One failing test never stops the others.
  • Good tests are fast, independent, repeatable and self-validating; they test behavior, cover boundaries, and have names that read like a specification.

Next: Build Tools: Maven and Gradle, where you'll see how real projects manage dependencies like JUnit, compile code, run tests and package JAR files.