Skip to lesson

JUnit 5 first look

A custom check method in main works well for a single file, but real projects have hundreds of classes and thousands of tests. JUnit 5 (also called JUnit Jupiter) is the standard Java test framework that runs each test independently, catches unexpected exceptions, and shows green/red tree reports in your IDE.

Why test frameworks beat a giant main method

A unit test is a small piece of code that calls one method with a known input and checks that the result matches the expected output.

If you put twenty checks inside main and the third check throws an unexpected ArrayIndexOutOfBoundsException, the program crashes immediately and checks 4 through 20 never run. You also have to keep test code mixed inside your solution class or comment it out before submitting.

Example 1 · How test isolation keeps running remaining @Test methods after a failure

TestIsolationReportDemo.javaJava
import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;
public class TestIsolationReportDemo {    @Retention(RetentionPolicy.RUNTIME)    @interface Test {}
    static void assertEquals(int expected, int actual) {        if (expected != actual) {            throw new AssertionError("expected: <" + expected + "> but was: <" + actual + ">");        }    }
    // Buggy method: initializes max = 0    static int buggyMax(int[] nums) {        int max = 0;        for (int x : nums) {            if (x > max) max = x;        }        return max;    }
    @Test    void normalPositiveCase() {        assertEquals(9, buggyMax(new int[]{3, 9, 4}));    }
    @Test    void allNegativeCase() {        assertEquals(-3, buggyMax(new int[]{-8, -3, -10}));    }
    @Test    void singlePositiveElement() {        assertEquals(7, buggyMax(new int[]{7}));    }
    public static void main(String[] args) throws Exception {        String[] names = {"normalPositiveCase", "allNegativeCase", "singlePositiveElement"};        int passed = 0;        int failed = 0;        for (String name : names) {            Method m = TestIsolationReportDemo.class.getDeclaredMethod(name);            try {                m.invoke(new TestIsolationReportDemo());                passed++;                System.out.println("PASS: " + name + "()");            } catch (InvocationTargetException e) {                failed++;                System.out.println("FAIL: " + name + "() -> " + e.getCause().getMessage());            }        }        System.out.println("Summary: " + passed + " passed, " + failed + " failed");    }}
Output
PASS: normalPositiveCase()
FAIL: allNegativeCase() -> expected: <-3> but was: <0>
PASS: singlePositiveElement()
Summary: 2 passed, 1 failed

What this code does

  • Even though allNegativeCase() throws an AssertionError, the test runner catches it, records expected: <-3> but was: <0>, and still runs singlePositiveElement().
  • Reading the failure line expected: <-3> but was: <0> immediately points to the int max = 0 initialization bug.
  • Isolation: One crashing test never blocks the rest of the test suite from running.
  • Separation: Tests live in a separate class (e.g., ArrayUtilsTest.java) so production or submission code stays clean.
  • IDE integration: IntelliJ IDEA, VS Code, and Eclipse show a clickable green/red tree for every @Test method.

A unit testing framework like JUnit 5 solves both problems:

  1. Test isolation: Every method marked with @Test runs on its own fresh instance of the test class. If one @Test method fails or crashes, JUnit records the failure and still runs all remaining @Test methods.
  2. Rich failure reports: When an assertion fails, JUnit prints the test name, the exact line number in the stack trace, and a diff showing expected: <5> but was: <4>.

@Test, assertEquals, assertArrayEquals, and assertThrows

In JUnit 5 (org.junit.jupiter.api.*), you mark each test method with @Test. Test methods take no parameters (unless parameterized), return void, and do not need to be public in JUnit 5 (package-private is the convention).

Example 2 · Writing @Test methods with assertEquals, assertArrayEquals, and assertThrows

JUnitFirstLookDemo.javaJava
import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.reflect.Method;import java.util.Arrays;import java.util.Objects;
// In an IDE with JUnit 5 on the classpath, you replace the mini-declarations below with:// import org.junit.jupiter.api.Test;// import static org.junit.jupiter.api.Assertions.*;public class JUnitFirstLookDemo {    @Retention(RetentionPolicy.RUNTIME)    @interface Test {}
    @FunctionalInterface    interface Executable { void execute() throws Throwable; }
    static void assertEquals(Object expected, Object actual) {        if (!Objects.equals(expected, actual)) {            throw new AssertionError("expected: <" + expected + "> but was: <" + actual + ">");        }    }
    static void assertArrayEquals(int[] expected, int[] actual) {        if (!Arrays.equals(expected, actual)) {            throw new AssertionError("expected: <" + Arrays.toString(expected)                + "> but was: <" + Arrays.toString(actual) + ">");        }    }
    static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable code) {        try {            code.execute();        } catch (Throwable thrown) {            if (expectedType.isInstance(thrown)) {                return expectedType.cast(thrown);            }            throw new AssertionError("Unexpected exception type thrown: " + thrown.getClass().getSimpleName());        }        throw new AssertionError("Expected " + expectedType.getSimpleName() + " to be thrown, but nothing was thrown.");    }
    // --- Production methods under test ---    static int maxElement(int[] nums) {        if (nums == null || nums.length == 0) {            throw new IllegalArgumentException("nums must not be empty");        }        int max = nums[0];        for (int i = 1; i < nums.length; i++) {            max = Math.max(max, nums[i]);        }        return max;    }
    static int[] reverseCopy(int[] nums) {        int[] out = new int[nums.length];        for (int i = 0; i < nums.length; i++) {            out[i] = nums[nums.length - 1 - i];        }        return out;    }
    // --- JUnit 5 style @Test methods ---    @Test    void maxOfAllNegativesReturnsLargestNegative() {        assertEquals(-2, maxElement(new int[]{-9, -2, -5}));    }
    @Test    void reverseCopyReversesOrder() {        assertArrayEquals(new int[]{4, 3, 2, 1}, reverseCopy(new int[]{1, 2, 3, 4}));    }
    @Test    void maxOfEmptyArrayThrowsIllegalArgument() {        IllegalArgumentException ex = assertThrows(            IllegalArgumentException.class,            () -> maxElement(new int[]{})        );        assertEquals("nums must not be empty", ex.getMessage());    }
    public static void main(String[] args) throws Exception {        String[] testOrder = {            "maxOfAllNegativesReturnsLargestNegative",            "reverseCopyReversesOrder",            "maxOfEmptyArrayThrowsIllegalArgument"        };        for (String name : testOrder) {            Method m = JUnitFirstLookDemo.class.getDeclaredMethod(name);            if (m.isAnnotationPresent(Test.class)) {                m.invoke(new JUnitFirstLookDemo());                System.out.println("[PASS] " + name + "()");            }        }    }}
Output
[PASS] maxOfAllNegativesReturnsLargestNegative()
[PASS] reverseCopyReversesOrder()
[PASS] maxOfEmptyArrayThrowsIllegalArgument()

What this code does

  • Each @Test method focuses on one behaviour and has a self-explanatory name (maxOfAllNegativesReturnsLargestNegative).
  • assertThrows returns the caught exception object, allowing you to also assert on ex.getMessage() if desired.

Example 3 · Why putting expected first in assertEquals(expected, actual) matters

ExpectedFirstOrderDemo.javaJava
public class ExpectedFirstOrderDemo {    static String formatFailure(int expected, int actual) {        return "AssertionFailedError: expected: <" + expected + "> but was: <" + actual + ">";    }
    public static void main(String[] args) {        int actualFromBuggyCode = 0;        int expectedBySpec = -3;
        System.out.println("Correct order   assertEquals(expected, actual):");        System.out.println("  " + formatFailure(expectedBySpec, actualFromBuggyCode));
        System.out.println("Backwards order assertEquals(actual, expected):");        System.out.println("  " + formatFailure(actualFromBuggyCode, expectedBySpec));    }}
Output
Correct order   assertEquals(expected, actual):
  AssertionFailedError: expected: <-3> but was: <0>
Backwards order assertEquals(actual, expected):
  AssertionFailedError: expected: <0> but was: <-3>

What this code does

  • JUnit's assertEquals(expected, actual) always labels the first argument as expected and the second argument as but was.
  • Swapping the two arguments still fails when they differ, but prints a misleading error message that says your test expected the wrong value.
  1. Import org.junit.jupiter.api.Test; and static org.junit.jupiter.api.Assertions.*;.
  2. Write a descriptive method name like void maxOfAllNegativesReturnsLargestNegative() and annotate it with @Test.
  3. Put expected first, actual second in assertEquals(expected, actual) and assertArrayEquals(expected, actual).
  4. Use assertThrows(IllegalArgumentException.class, () -> solve(invalidInput)) to verify error handling.

Inside a @Test method, you verify results using static methods from org.junit.jupiter.api.Assertions.*:

  • assertEquals(expected, actual): Notice the parameter order! In JUnit, expected always comes first and actual comes second.
  • assertArrayEquals(expectedArray, actualArray): Compares two arrays element by element.
  • assertThrows(ExceptionClass.class, () -> methodCall()): Verifies that the lambda expression throws the specified exception type (or a subclass of it), and fails the test if no exception or the wrong exception is thrown.

Adding JUnit 5 in your IDE without a build tool (and reading reports)

Later in the programme you will manage dependencies with Maven and Gradle, where JUnit 5 is included in pom.xml or build.gradle. When working in a plain Java project without a build tool, modern IDEs can still download the JUnit 5 JAR (junit-platform-console-standalone.jar or junit-jupiter) for you in two clicks:

  • IntelliJ IDEA: Place your cursor on @Test (shown in red), press Alt+Enter (Windows/Linux) or Option+Enter (macOS), and choose Add 'JUnit5.8.1' to classpath.
  • VS Code (Extension Pack for Java): Open the Testing beaker icon in the left sidebar and click Enable Java Tests → JUnit Jupiter; VS Code downloads the standalone JAR into your project's lib/ folder.

When a test fails, JUnit throws an org.opentest4j.AssertionFailedError whose message follows the exact format: org.opentest4j.AssertionFailedError: expected: <12> but was: <4> Because expected was passed first in assertEquals(12, buggyMax(arr)), the failure report reads naturally. If you accidentally swap the arguments (assertEquals(actual, expected)), the report prints expected: <4> but was: <12>, which confuses everyone reading the log!

In the runnable examples below, our single-file classes include lightweight @Test, assertEquals, and assertThrows definitions so you can compile and run them directly with standard javac --release 17, while using the exact JUnit 5 call syntax and failure report format.

Next step

Check your understanding

10 quick questions