How to compare LISTS recursively ignoring given fields using assertJ?
Asked Answered
S

4

13

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?

Scintillate answered 22/6, 2017 at 19:17 Comment(0)
S
5

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

Statued answered 23/6, 2017 at 3:10 Comment(0)
S
13

Starting AssertJ Core 3.20.0 you can use usingRecursiveFieldByFieldElementComparatorIgnoringFields(String... fields) method:

assertThat(actualList)
        .usingRecursiveFieldByFieldElementComparatorIgnoringFields("field1", "field2")
        .isEqualTo(expectedList);
Spark answered 1/7, 2022 at 21:15 Comment(0)
S
5

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

Statued answered 23/6, 2017 at 3:10 Comment(0)
D
1

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());
}
Drawshave answered 22/11, 2017 at 11:12 Comment(0)
T
0

@Arkadiusz example didn't work for me. Also, I had a recursive problems with lists, so my solution is tailored to that case. So what I did was (Kotlin code):

private fun recursiveListComparatorFactory(vararg ignoreFields: String): Comparator<List<*>> {
    return Comparator { o1, o2 ->
        assertThat(o1).hasSameSizeAs(o2)
        for (i in o1.indices) {
            assertThat(o1[i]).usingComparatorForType(recursiveListComparatorFactory(*ignoreFields), List::class.java).isEqualToIgnoringGivenFields(o2[i], *ignoreFields)
        }
        0 // return
    }
}

and then just call:

val ignoreFields = ["id", "version"]
assertThat(o1).usingComparatorForType(recursiveListComparatorFactory(ignoreFields), List::class.java).isEqualToIgnoringGivenFields(o2, ignoreFields)
Tical answered 21/1, 2019 at 9:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.