Search code examples
javalistkotlinassertj

How to compare lists in any order without null fields in assertj?


I usually comprare two lists that are equal using the following way:

assertThat(actual)
    .usingRecursiveComparison
    .ignoringExpectedNullFields
    .isEqualTo(expected)

Now I want to compare lists that have all the same elements that are positioned at the different positions. I found that I can do it like this:

assertThat(actual)
    .containsExactlyInAnyOrderElementsOf(expected)

But this way it does not ignore null fields like the first way. How can I achieve that?

I tried using the same chaining methods but it seems like it is not affecting the results


Solution

  • Not sure what your use case for ignoring null is, but if you really want to pursue that route, you can combine .ignoringExpectedNullFields() and ..ignoringCollectionOrder(). For example, the following test is successful:

    val actual = listOf("one", "four", "three", "two")
    val expected = listOf("one", "two", "three", null)
    
    assertThat(actual)
        .usingRecursiveComparison()
        .ignoringExpectedNullFields()
        .ignoringCollectionOrder()
        .isEqualTo(expected)
    

    Note that both actual and expected must have the same size – if you remove "four" from actual, for example, the test will fail.