How To Write Unit Tests - Asserting List Equality
There are multiple implementations of lists, some of which are mutable and resizable. Unit tests that cover lists should take all implementations into account.
This article explains how to properly assert list equality.
Scenario
- Order record
- Repository class returns a list of Order instances from a Database
- Database interface is injected as a dependency to Repository and is of no further importance
- A unit test that asserts if the returned value is as expected.
Asserting Equality of the List Size Is Not Enough
The following unit test checks if the returned list size is as expected. The unit test passes.
The same unit test passes for the code that changes the list elements, but does not change the list size.
Asserting Equality of a List Element Is Not Enough
The following unit test checks if the first element of the returned list is as expected. The unit test passes.
The same unit test passes for the code that adds another element to the list.
Expected List Same as Given List
As explained in another blog post about expected values, comparing a given value to the actual value can also lead to false positives.
Asserting Lists Are Deeply Equal
The following unit test will not pass for faulty code.
This example compares two list instances. Mockito assertEquals method asserts that lists are deeply equal.
- Create a new instance of the expected list object
- Create a new instance of all objects in the expected list
- Assert that lists are "deeply" equal (all elements, order of elements and size are equal)
Full code samples can be found on GitHub.