In a unit test, I want to verify that two lists contain the same elements. The list to test is build of a list of Person
objects, where one field of type Stri
If the number of elements must be the same, then it would be better to compare sets:
List people = getPeopleFromDatabasePseudoMethod();
Set expectedValues = new HashSet<>(Arrays.asList("john", "joe", "bill"));
assertEquals(expectedValues,
people.stream().map(Person::getName).collect(Collectors.toSet()));
The equals
method for properly implemented sets should be able to compare different types of sets: it just checks whether the contents is the same (ignoring the order of course).
Using assertEquals
is more convenient as in case of failure an error message will contain the string representation of your set.