Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare LISTS recursively ignoring given fields using assertJ?

Firstly, this is not a duplicate of this question. There, it is asked specifically for an object. I want to do this for a Container, specifically a List.

So, I know I can ignore a field when using usingElementComparatorIgnoringFields() But this won't do a recursive comparison.

I know I can use usingRecursiveFieldByFieldElementComparator(). But this will not allow me to exclude a given field.

How can I compare recursively, ignoring a field?

like image 343
orrymr Avatar asked Jun 22 '17 19:06

orrymr


2 Answers

this is going to be in the next AssertJ Core version: https://github.com/joel-costigliola/assertj-core/issues/1002

like image 196
Joel Costigliola Avatar answered Oct 15 '22 09:10

Joel Costigliola


Meanwhile you could write this:

assertThat(actualList)
            .usingElementComparator(recursiveIgnoringComparator("excludedField1", "excludedField2", "excludedField3"))
            .containsExactlyInAnyOrder(expectedList);
}

private Comparator<T> recursiveIgnoringFieldsComparator(String... fieldNames) {
    final Map<String, Comparator<?>> comparatorByPropertyOrField =
            Arrays.stream(fieldNames)
                    .collect(toMap(
                            name -> name,
                            name -> (o1, o2) -> 0
                    ));

    return new RecursiveFieldByFieldComparator(comparatorByPropertyOrField, new TypeComparators());
}
like image 30
Arkadiusz Masiakiewicz Avatar answered Oct 15 '22 08:10

Arkadiusz Masiakiewicz