Skip to main content
Quick Reference

JUnit Cheatsheet

JUnit 5 on one page — Jupiter tests, lifecycle, assertions, parameters, and the traps around argument order, arrays, and static state.

10 sections 10 tables 14 code snippets

A Jupiter test

Expected, then actual

@Test
void adds() {
    assertEquals(4, add(2, 2));
}

Static import

import static org.junit.jupiter.api.Assertions.assertEquals;

What runs

PieceMeaning
@TestMarks one method. Package-visible is enough. Private is not discovered
Packageorg.junit.jupiter.api. The JUnit 4 package is org.junit
ReturnA @Test method returns void
Enginejunit-jupiter-engine must be on the test runtime path. The API jar compiles the annotations and runs nothing
AggregatorThe junit-jupiter artifact brings the API, params, and the engine
VintageJUnit 4 tests need junit-vintage-engine on that same path

This page is JUnit 5 Jupiter. Mockito and Spring test slices are left out.

Lifecycle

Fresh cart before each test

@BeforeEach
void reset() {
    cart = new Cart();
}

Once per class

# @BeforeAll is static unless the class is PER_CLASS

When each hook runs

HookWhen
@BeforeEachBefore each test, on that test instance
@AfterEachAfter each test, including when the assertion failed
@BeforeAllOnce, before any test in the class. Static by default
@AfterAllOnce, after every test in the class. Static by default
PER_METHODThe default. A new instance for every test, so instance fields start over
PER_CLASSOne instance for the class. Then @BeforeAll can be an instance method

Assertions

Whole values

assertEquals(4, add(2, 2));

Array contents

# assertArrayEquals(expected, actual)

Which method

CallChecks
assertEqualsequals. Expected first, actual second, message last
assertSame== on the two references
assertArrayEqualsSame length and pairwise elements. assertEquals on two arrays is reference equality
assertTrueThe boolean is true
deltaThird argument for float and double. An exact compare can reject 0.1 + 0.2 versus 0.3
assertNullThe reference is null. An empty string is a value

Exceptions

Type, then the call

assertThrows(IllegalArgumentException.class, () -> cart.add(-1));

What the matcher accepts

CaseResult
Matching typePasses, and returns the exception so the message can be checked
SubclassA thrown subclass passes, because the check uses isInstance
Nothing thrownFails
Wrong typeFails, and the unexpected exception is reported
MessageassertEquals on getMessage() is the whole string
JUnit 4@Test(expected = ...) is the old form. Jupiter @Test has no expected element

Several checks

Keep going after one miss

assertAll(
    () -> assertEquals(2, cart.size()),
    () -> assertEquals(0, cart.total())
);

One failure or all of them

ToolBehavior
Sequential assertsThe first failure leaves the method. Later checks never run
assertAllRuns every lambda, then reports every failure together
assertTimeoutSame thread. Waits for the call to finish, then fails if it was too slow
PreemptiveassertTimeoutPreemptively fails when the limit is hit, from another thread
@TimeoutA declarative limit. The default runs that test on a separate thread
HangA call that never returns keeps assertTimeout waiting with it

Parameters

One method, three inputs

@ParameterizedTest
@ValueSource(ints = {1, 3, 5})
void acceptsOdd(int n) {
    assertTrue(n % 2 == 1);
}

Where the arguments come from

SourceSupplies
@ParameterizedTestRuns once per argument set. It needs junit-jupiter-params
@ValueSourceOne column of literals. An annotation value cannot be null
@CsvSourceSeveral columns split on commas. A comma inside a field is wrapped in single quotes
@MethodSourceA static factory, unless the class is PER_CLASS. The default name matches the test
@NullSourceOne null argument. Not valid on a primitive parameter
AggregatorThe junit-jupiter artifact already includes params

Assumptions

Skip when the machine cannot run this

assumeTrue(online);

Skip versus fail

CallWhen the condition misses
assumeTrueSkips the rest of this test. The report says aborted, not failed
assumeFalseSkips when the condition is true
Later assertsDo not run after a failed assumption
assertTrueFails the test. Use it when the condition is the thing you mean to prove
Missing serviceAn assumption skips a test this machine cannot run
Classorg.junit.jupiter.api.Assumptions

Nested classes

A group inside the outer test

@Nested
class WhenEmpty {
    @Test
    void rejectsRemove() {
        assertThrows(IllegalStateException.class, cart::remove);
    }
}

Inner class rules

RuleWhy
Non-static@Nested must be an inner class. A static nested class is rejected
Outer hooksThe outer @BeforeEach runs before each nested test too
FieldsThe inner class can read fields of the outer instance
@BeforeAllA static one is legal in a nested class from Java 16. An instance one still needs PER_CLASS
ReportNesting shows up as a path of display names
DeeperA nested class can contain another @Nested class

Names and order

Turn @Order on

@TestMethodOrder(OrderAnnotation.class)

Labels, skips, sequence

KnobEffect
@DisplayNameReplaces the method name in the report
@DisabledSkips the method or the whole class. The reason string is optional
@OrderA number on a method. It does nothing until the class has @TestMethodOrder(OrderAnnotation.class)
Default orderDeterministic, and intentionally not the order of the methods in the file
@RepeatedTestRuns the same method n times. A RepetitionInfo parameter receives the index
@TagA label for the build filter. The tag alone does not skip the test

Interview traps

Message last

# assertEquals(expected, actual, "2 + 2")

The JUnit 4 import

# org.junit.Test is invisible to Jupiter

Traps worth memorising

TrapWhat happensPrefer
org.junit.TestJupiter does not discover the JUnit 4 annotationorg.junit.jupiter.api.Test, or add the vintage engine
Message firstThat was JUnit 4. In Jupiter a leading string becomes the expected valueassertEquals(expected, actual, message)
assertEquals on arraysUses equals, which for an array is identityassertArrayEquals
private @TestThe method is not discoveredPackage-visible or public
Static fieldThe next test sees the mutation. Only the instance is newKeep state on the instance, or reset it in @BeforeEach
Non-static @BeforeAllFails under the default PER_METHOD lifecycleMake it static, or set @TestInstance(PER_CLASS)

How to use this page: use Jupiter annotations, put the expected value first, and keep mutable state off static fields.