Skip to main content

Assert list size

When testing collection sizes with JUnit Jupiter, it's easy to make mistakes with argument order or write verbose assertions. AssertJ provides more expressive and less error-prone alternatives.

Redundant null checks

Checking for null before checking collection size is redundant, as a null collection would fail the size check anyway.

AssertListSize.java
import org.junit.jupiter.api.Test;

import java.util.List;

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

class AssertListSize {

List<String> list = List.of("a", "b", "c");

@Test
void assertListSize() {
assertNotNull(list);
assertEquals(3, list.size());
}
}
warning

The assertNotNull(list) check is redundant. If the list were null, assertEquals(3, list.size()) would throw a NullPointerException anyway.

Confusing failure messages

Using JUnit's assertEquals() with the actual and expected values swapped leads to confusing error messages.

AssertListSize.java
import org.junit.jupiter.api.Test;

import java.util.List;

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

class AssertListSize {

List<String> list = List.of("a", "b", "c");

@Test
void incorrectArgumentOrder() {
assertEquals(list.size(), 4);
}
}
danger

The arguments are backwards. JUnit 5's assertEquals() expects the expected value first, then the actual value. This produces a confusing error: expected: <3> but was: <4> when it should be expected: <4> but was: <3>.