Assertions
An assertion is the line in a test that states what the result should be. If reality disagrees, the assertion throws and the test fails with a message explaining the difference.
Detailed Explanation
A test without an assertion proves almost nothing. It proves the code did not throw. Assertions are what turn "it ran" into "it is correct", so they are the part of a test that carries the actual meaning.
JUnit 5 ships its assertions as static methods on org.junit.jupiter.api.Assertions. Most teams static-import them so tests read like sentences. The common ones are assertEquals, assertTrue, assertFalse, assertNull, assertNotNull, assertThrows, and assertAll.
Argument order trips up anyone coming from JUnit 4. In JUnit 5 the expected value comes first, the actual value second, and the optional failure message last. JUnit 4 put the message first. Swapping expected and actual does not fail the test, it only produces a backwards error message that sends you hunting in the wrong direction.
assertEquals uses equals, not ==. For a class with a proper equals implementation, or for a record where the compiler writes one, comparing two separately constructed objects works as you would hope. For a class that never overrode equals, the comparison falls back to identity and fails even when the fields match. Floating point needs the three-argument form, assertEquals(expected, actual, delta), because 0.1 + 0.2 is not 0.3 in binary.
Two assertions are worth learning properly.
assertThrows captures the exception and hands it back so you can inspect it. This replaced JUnit 4's @Test(expected = X.class), which passed if the exception came from anywhere in the method, including from setup code that was never meant to throw. assertThrows narrows the check to one lambda.
assertAll runs a group of assertions and reports every failure instead of stopping at the first. Without it, a test that checks five fields tells you about one wrong field per run, and you fix them one slow cycle at a time.
The message argument is worth spending words on. assertTrue(user.isActive()) fails with "expected true, was false", which tells you nothing you did not already know. Passing a message, or better a Supplier<String> that builds the message lazily only on failure, turns a wasted debugging hour into a five-second read.
Many teams prefer AssertJ over the built-in assertions. AssertJ is a separate library with a fluent style, assertThat(order.total()).isEqualTo(2248), and gives far richer failure output for collections, strings, and exceptions. It also chains, so assertThat(items).hasSize(3).contains("mug") reads in one line. It is an extra dependency, and mixing both styles inside one suite makes the code inconsistent, so pick one per project.
The cost of assertions is mostly discipline. Over-asserting on incidental details, such as the exact wording of a log message, produces tests that break every time someone edits unrelated text. Assert the behaviour you promised, not every field you happen to see.
Code Examples
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class AccountAssertionsTest {
// A record gets equals, hashCode and toString from the compiler,
// which is what makes assertEquals on whole objects useful.
record Account(String id, long balanceCents) {
Account withdraw(long cents) {
if (cents > balanceCents) {
throw new IllegalArgumentException("insufficient funds");
}
return new Account(id, balanceCents - cents);
}
}
@Test
void withdrawalLeavesTheExpectedBalance() {
var account = new Account("ACC-1", 10_000);
var after = account.withdraw(2_500);
// assertAll reports every failing check, not only the first one.
assertAll("account after withdrawal",
() -> assertEquals("ACC-1", after.id()),
() -> assertEquals(7_500, after.balanceCents()),
() -> assertTrue(after.balanceCents() < account.balanceCents(),
() -> "balance should drop, was " + after.balanceCents()));
}
@Test
void overdraftIsRejected() {
var account = new Account("ACC-1", 500);
// assertThrows returns the exception so you can assert on it.
// JUnit 4 used @Test(expected = IllegalArgumentException.class),
// which could not tell which line threw.
var thrown = assertThrows(IllegalArgumentException.class,
() -> account.withdraw(900));
assertEquals("insufficient funds", thrown.getMessage());
}
@Test
void floatingPointNeedsATolerance() {
double total = 0.1 + 0.2; // 0.30000000000000004 in binary floating point
// The two-argument form would fail here. The third argument is the delta.
assertEquals(0.3, total, 1e-9);
}
}Common Gotchas
Swapped expected and actual still passes
JUnit cannot tell which argument you meant. The test goes green or red correctly, but a failure reports "expected 7500, was 10000" with the roles reversed, which wastes debugging time.
`assertEquals` on a class without `equals` compares identity
two objects holding identical field values fail the assertion because `Object.equals` is reference equality. Use a record, or implement `equals` and `hashCode` together.
`assertTrue` on a compound condition hides which half broke
`assertTrue(a.isPaid() && a.isShipped())` fails with "expected true, was false". Split it into two assertions inside `assertAll` and the report names the failing one.