How do I test Collections, Lists, Maps, and Sets in JUnit?

Testing Collections in JUnit

In JUnit, you usually test collections with assertions such as:

  • assertEquals
  • assertTrue
  • assertFalse
  • assertIterableEquals
  • assertArrayEquals
  • assertThrows

If you are using JUnit 5, import assertions from:

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

1. Testing a List

Use assertEquals when order matters.

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.assertTrue;

class ListTest {

    @Test
    void shouldContainExpectedItemsInOrder() {
        List<String> names = List.of("Alice", "Bob", "Charlie");

        assertEquals(3, names.size());
        assertEquals("Alice", names.get(0));
        assertEquals(List.of("Alice", "Bob", "Charlie"), names);
        assertTrue(names.contains("Bob"));
    }
}

List.equals() checks:

  1. Same size
  2. Same elements
  3. Same order

So this works well:

assertEquals(List.of("Alice", "Bob"), actualList);

2. Testing a Set

A Set does not guarantee order, so compare it with another set.

import org.junit.jupiter.api.Test;

import java.util.Set;

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

class SetTest {

    @Test
    void shouldContainExpectedUniqueItems() {
        Set<String> roles = Set.of("ADMIN", "USER");

        assertEquals(2, roles.size());
        assertTrue(roles.contains("ADMIN"));
        assertEquals(Set.of("USER", "ADMIN"), roles);
    }
}

Set.equals() ignores order, so this passes:

assertEquals(Set.of("ADMIN", "USER"), actualSet);

3. Testing a Map

Use assertEquals to compare maps by key/value pairs.

import org.junit.jupiter.api.Test;

import java.util.Map;

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

class MapTest {

    @Test
    void shouldContainExpectedEntries() {
        Map<String, Integer> scores = Map.of(
                "Alice", 95,
                "Bob", 88
        );

        assertEquals(2, scores.size());
        assertEquals(95, scores.get("Alice"));
        assertTrue(scores.containsKey("Bob"));
        assertEquals(Map.of("Bob", 88, "Alice", 95), scores);
    }
}

Map.equals() checks that both maps contain the same mappings, regardless of entry order.

assertEquals(Map.of("Alice", 95, "Bob", 88), actualMap);

4. Testing Collection Size

import org.junit.jupiter.api.Test;

import java.util.List;

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

class CollectionSizeTest {

    @Test
    void shouldHaveExpectedSize() {
        List<String> items = List.of("A", "B", "C");

        assertEquals(3, items.size());
    }
}

5. Testing Empty Collections

import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.List;

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

class EmptyCollectionTest {

    @Test
    void shouldBeEmpty() {
        List<String> items = Collections.emptyList();

        assertTrue(items.isEmpty());
    }
}

You can also use:

assertEquals(0, items.size());

But this is usually more readable:

assertTrue(items.isEmpty());

6. Testing That a Collection Contains an Item

import org.junit.jupiter.api.Test;

import java.util.List;

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

class ContainsTest {

    @Test
    void shouldContainExpectedItem() {
        List<String> names = List.of("Alice", "Bob");

        assertTrue(names.contains("Alice"));
    }
}

For negative checks:

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

// ...

assertFalse(names.contains("Charlie"));

7. Testing List Order Explicitly

You can use assertIterableEquals for lists and other iterable collections.

import org.junit.jupiter.api.Test;

import java.util.List;

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

class IterableTest {

    @Test
    void shouldMatchExpectedOrder() {
        List<String> actual = List.of("A", "B", "C");

        assertIterableEquals(List.of("A", "B", "C"), actual);
    }
}

This checks both contents and order.


8. Testing Same Contents Regardless of Order

For lists where order does not matter, convert both to sets:

import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.Set;

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

class UnorderedListTest {

    @Test
    void shouldHaveSameItemsIgnoringOrder() {
        List<String> actual = List.of("B", "A", "C");

        assertEquals(Set.of("A", "B", "C"), Set.copyOf(actual));
    }
}

Be careful: converting to a set removes duplicates.

If duplicates matter but order does not, sort both lists first:

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

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

class SortedListTest {

    @Test
    void shouldHaveSameItemsIgnoringOrderButKeepingDuplicates() {
        List<String> actual = new ArrayList<>(List.of("B", "A", "A"));
        List<String> expected = new ArrayList<>(List.of("A", "A", "B"));

        actual.sort(Comparator.naturalOrder());
        expected.sort(Comparator.naturalOrder());

        assertEquals(expected, actual);
    }
}

9. Testing a Mutable Collection

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

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

class MutableListTest {

    @Test
    void shouldAddItemToList() {
        List<String> items = new ArrayList<>();

        items.add("Book");

        assertEquals(1, items.size());
        assertTrue(items.contains("Book"));
    }
}

10. Testing Exceptions for Immutable Collections

Collections created with List.of, Set.of, or Map.of are immutable.

import org.junit.jupiter.api.Test;

import java.util.List;

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

class ImmutableCollectionTest {

    @Test
    void shouldThrowWhenModifyingImmutableList() {
        List<String> items = List.of("A", "B");

        assertThrows(UnsupportedOperationException.class, () -> {
            items.add("C");
        });
    }
}

11. Testing with AssertJ

If your project uses AssertJ, collection assertions are often more readable.

Maven dependency:

<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.26.3</version>
    <scope>test</scope>
</dependency>

Example:

import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.Map;
import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;

class AssertJCollectionTest {

    @Test
    void shouldTestCollectionsFluently() {
        List<String> names = List.of("Alice", "Bob");

        assertThat(names)
                .hasSize(2)
                .contains("Alice")
                .containsExactly("Alice", "Bob");

        Set<String> roles = Set.of("ADMIN", "USER");

        assertThat(roles)
                .containsExactlyInAnyOrder("USER", "ADMIN");

        Map<String, Integer> scores = Map.of("Alice", 95, "Bob", 88);

        assertThat(scores)
                .hasSize(2)
                .containsEntry("Alice", 95)
                .containsKey("Bob");
    }
}

AssertJ is especially useful for:

assertThat(list).containsExactly("A", "B");
assertThat(list).containsExactlyInAnyOrder("B", "A");
assertThat(set).contains("A");
assertThat(map).containsEntry("key", "value");
assertThat(collection).isEmpty();

Quick Reference

What you want to test JUnit assertion
List equals expected order assertEquals(expectedList, actualList)
Iterable equals expected order assertIterableEquals(expected, actual)
Set contains same items assertEquals(expectedSet, actualSet)
Map contains same entries assertEquals(expectedMap, actualMap)
Collection has size assertEquals(expectedSize, collection.size())
Collection is empty assertTrue(collection.isEmpty())
Collection contains item assertTrue(collection.contains(item))
Collection does not contain item assertFalse(collection.contains(item))

Recommended Style

For standard JUnit 5 tests:

assertEquals(List.of("A", "B"), actualList);
assertEquals(Set.of("A", "B"), actualSet);
assertEquals(Map.of("A", 1, "B", 2), actualMap);
assertTrue(actualList.contains("A"));
assertTrue(actualList.isEmpty());

For more readable collection tests, use AssertJ:

assertThat(actualList).containsExactly("A", "B");
assertThat(actualList).containsExactlyInAnyOrder("B", "A");
assertThat(actualMap).containsEntry("A", 1);

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.