Explain Codes LogoExplain Codes Logo

Assert equals between 2 Lists in Junit

java
assertj
junit
testing
Nikita BarsukovbyNikita Barsukov·Jan 29, 2025
TLDR

Check List equality disregarding order:

Assert.assertTrue(list1.containsAll(list2) && list2.containsAll(list1));

For identical order validation:

Assert.assertEquals(list1, list2);

These methods amply verify list equality in different contexts.

Comparing Lists in JUnit

When it comes to comparing Lists in JUnit, there are subtle and important differences depending on whether you're checking content only, or content with order.

Content and Order: Fast & Furious

assertThat(list1, is(list2)); // "List matching sick ride bro! 🚗💨"

Asserts two lists are identical in both order and content. Requires importing static org.hamcrest.MatcherAssert.assertThat; and static org.hamcrest.Matchers.is;.

Just Content: Taking the Scenic Route

assertThat(new HashSet<>(list1), is(new HashSet<>(list2))); // "I find your lack of order disturbing ⚔️"

This does not account for the order, only content.

Handling Null and Custom Objects

When dealing with custom object lists or lists that contain null, make sure to have suitable equals method overridden, otherwise your test can 🧨 explode.

The Inequality Assertion: A Twist in the Tale

You can assert two lists are not identical with the not matcher:

assertThat(list1, not(list2)); // "These are not the lists you are looking for 🌌"

Asserting with AssertJ: The Fluent Assault

AssertJ allows for a more fluent style, in turn simplifying assertions, producing better error messages and enabling custom object list assertions irregardless of your equals.

The Order and the Content: The Dynamic Duo

assertThat(list1).containsExactlyElementsOf(list2);

AssertJ checks for equality in both content and order.

Efficiency: The Need For Speed

Single Line Setup

Generating expected lists in tests is simplified with the Arrays.asList.

List<String> expectedList = Arrays.asList("element1", "element2", "element3"); // "And voilà, we have a list! 🎩🐇"

Decoding Failed Tests: The Detective's Insight

Debugging becomes easier with assert method custom messages.

assertThat(list1, is(list2), () -> "Both lists are as identical as twins, right? Nope, they are not!");

Up-to-Date: Staying Relevant

Staying updated with the latest libraries, methodologies for a more robust testing practice. "Stay thirsty, my friends 🍹"

List Equality Nuances

Custom Objects: Transcending equals

When your lists contain custom objects, AssertJ provides methods to create a deeper comparison bypassing your equals.

assertThat(list1).usingRecursiveComparison().isEqualTo(list2); // "Let's take a deeper look inside your list 👁"

Collection Utilities: Your Sidekick

Use Apache Commons Collections and Google Guava - they provide an extensive set of collection manipulation methods.