Sub topic 5
Checking Results with Assertions
A test needs a way to say "this is the right answer" or "this is wrong." In JUnit 5 you do that with assertions. An assertion is a method call that checks one fact about your code. If the fact is true, the test keeps going. If the fact is false, the test stops and is marked as failed.
This chapter covers the assertions you will use most often, how to read their failure messages, and the small mistakes beginners tend to make with them.
Where Assertions Come From
All the standard assertions are static methods in one class, org.junit.jupiter.api.Assertions. A static method belongs to the class itself, so you call it without creating an object. Most people use a static import so they can write assertEquals(...) instead of Assertions.assertEquals(...).
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;You can also import every assertion at once with import static org.junit.jupiter.api.Assertions.*;. Importing each one by name makes it easier to see which checks a file uses.
How an Assertion Decides Pass or Fail
When an assertion fails, it throws an AssertionFailedError, which is a special exception. JUnit catches it, marks the test as failed, and prints the message. Any lines after the failed assertion in that test do not run.
The Code Under Test
The examples use the Calculator class from earlier chapters, plus one extra method that returns a list.
import java.util.ArrayList;
import java.util.List;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("divisor must not be zero");
}
return a / b;
}
public double average(int a, int b) {
return (a + b) / 2.0;
}
public List<Integer> evensUpTo(int limit) {
List<Integer> result = new ArrayList<>();
for (int i = 2; i <= limit; i += 2) {
result.add(i);
}
return result;
}
}The Core Assertions
The table lists the assertions you will reach for most often.
| Assertion | Passes when | Example |
|---|---|---|
| `assertEquals(expected, actual)` | the two values are equal | `assertEquals(5, calc.add(2, 3))` |
| `assertNotEquals(unexpected, actual)` | the two values differ | `assertNotEquals(0, calc.add(1, 1))` |
| `assertTrue(condition)` | the condition is `true` | `assertTrue(list.isEmpty())` |
| `assertFalse(condition)` | the condition is `false` | `assertFalse(list.contains(3))` |
| `assertNull(value)` | the value is `null` | `assertNull(map.get("missing"))` |
| `assertNotNull(value)` | the value is not `null` | `assertNotNull(calc)` |
| `assertSame(expected, actual)` | both are the very same object | `assertSame(a, a)` |
| `assertArrayEquals(expected, actual)` | two arrays hold equal items in order | `assertArrayEquals(new int[]{1, 2}, arr)` |
| `assertIterableEquals(expected, actual)` | two lists hold equal items in order | `assertIterableEquals(List.of(2, 4), list)` |
| `assertAll(...)` | every grouped check passes | see below |
| `fail(message)` | never; it always fails | `fail("should not get here")` |
assertEquals and the Order of Arguments
assertEquals takes the expected value first and the actual value second. The expected value is the answer you know is correct. The actual value is what your code really returned.
The order matters for the failure message. If you swap them, the test still passes or fails correctly, but the report says the wrong thing.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class AddTest {
@Test
void addReturnsSum() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertEquals(5, result);
}
}If add had a bug and returned 6, JUnit would print:
org.opentest4j.AssertionFailedError: expected: <5> but was: <6>Read it as "I expected 5, but the code gave me 6." With the arguments swapped, it would say "expected 6 but was 5", which points you the wrong way while debugging.
Comparing Decimal Numbers
Computers store numbers like double in a way that is not always exact. For example, 0.1 + 0.2 is 0.30000000000000004, not 0.3. To handle this, assertEquals has a version that takes a third value called a delta. The delta is how far apart the two numbers may be and still count as equal.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class DecimalTest {
@Test
void averageOfTwoNumbers() {
Calculator calculator = new Calculator();
assertEquals(2.5, calculator.average(2, 3), 0.0001);
}
@Test
void addingDecimals() {
assertEquals(0.3, 0.1 + 0.2, 0.0001);
}
}Without the delta, addingDecimals would fail.
assertTrue and assertFalse
These check a yes-or-no condition. They are handy, but their failure message is plain: expected: <true> but was: <false>. It does not say which values were involved. When you can, prefer a more specific assertion. assertEquals(3, list.size()) tells you the real size on failure, while assertTrue(list.size() == 3) does not.
Equal Versus Same
assertEquals uses the object's equals method. Two different String objects with the same letters are equal. assertSame checks that two variables point to the exact same object in memory. You will need assertEquals far more often.
Comparing Lists and Arrays
Arrays in Java do not compare their contents with equals. Use assertArrayEquals for arrays. For lists, plain assertEquals works because List compares its items, and assertIterableEquals also works for any collection you can loop over.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
import java.util.List;
import org.junit.jupiter.api.Test;
class CollectionTest {
private final Calculator calculator = new Calculator();
@Test
void evensUpToSix() {
List<Integer> evens = calculator.evensUpTo(6);
assertEquals(List.of(2, 4, 6), evens);
assertIterableEquals(List.of(2, 4, 6), evens);
}
@Test
void arraysCompareByContent() {
int[] expected = {2, 4};
int[] actual = {2, 4};
assertArrayEquals(expected, actual);
}
}Adding Your Own Failure Message
Every assertion accepts an optional last argument: a message that JUnit prints if the check fails. A good message explains what the check means.
assertEquals(5, calculator.add(2, 3), "2 + 3 should be 5");Building a message costs a little time, even when the test passes. If the message is expensive to make, pass a lambda instead. A lambda is a short piece of code written as () -> ... that runs only when needed. JUnit calls it only if the assertion fails.
assertEquals(5, calculator.add(2, 3), () -> "add failed for inputs " + 2 + " and " + 3);Grouping Checks with assertAll
Normally the first failed assertion stops the test. Sometimes you want to see every problem at once, such as when checking several fields of one result. assertAll runs a group of checks and reports all the failures together.
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.util.List;
import org.junit.jupiter.api.Test;
class GroupedTest {
@Test
void evensUpToTenHasExpectedShape() {
Calculator calculator = new Calculator();
List<Integer> evens = calculator.evensUpTo(10);
assertAll("evens up to 10",
() -> assertEquals(5, evens.size()),
() -> assertEquals(2, evens.get(0)),
() -> assertEquals(10, evens.get(4)),
() -> assertFalse(evens.contains(7)));
}
}Each check is written as a lambda so JUnit can run them one by one and collect the results. If two of them fail, the report lists both under the heading "evens up to 10".
Using fail
fail always fails the test. You use it to mark a line the code should never reach, for example inside a branch that should be impossible. To check that code throws an exception, JUnit has a better tool, assertThrows, which the next chapter covers.
Common Mistakes
| Mistake | Why it hurts | Fix |
|---|---|---|
| Expected and actual swapped | The failure message is backwards | Put the known answer first |
| Comparing `double` with no delta | Rounding makes equal-looking numbers fail | Add a delta like `0.0001` |
| Using `assertEquals` on arrays | It compares object identity, not contents | Use `assertArrayEquals` |
| `assertTrue(a == b)` everywhere | The failure message hides the values | Use `assertEquals(a, b)` |
| A test with no assertion | It passes even when the code is wrong | Every test should check something |
Exercise
The method average(4, 5) should return 4.5. Write one assertion that checks this safely, with the arguments in the correct order.
Show answer
assertEquals(4.5, calculator.average(4, 5), 0.0001); The expected value 4.5 comes first, the actual result second, and the delta 0.0001 allows for tiny rounding differences in double values.
Exercise
A test has three assertEquals calls in a row, and the first one fails. How many of the three checks actually run, and how could you make JUnit report all three results?
Show answer
Only the first one runs, because a failed assertion throws an AssertionFailedError and stops the test. Wrapping the three checks in assertAll, each as a lambda such as () -> assertEquals(...), makes JUnit run all of them and report every failure together.
Exercise
Why is assertEquals(3, list.size()) usually better than assertTrue(list.size() == 3)?
Show answer
When it fails, assertEquals prints both values, for example "expected: <3> but was: <2>", so you can see the real size. assertTrue only says it expected true but got false, which hides the value you need for debugging.