Search code examples
javaassertj

Using AssertJ, how do I perform complex assertions on the contents of a list?


In AssertJ you can do the following to assert the contents of a list:

assertThat(list).extracting("name").containsExactlyInAnyOrder("Alice", "Bob");

I often find myself wanting to do more complex assertions on the elements themselves, e.g., asserting that Alice is a tall brunette and Bob is tiny and bald. What is the best way to do this using AssertJ?

My own solution is to do:

assertThat(list).extracting("name").containsExactlyInAnyOrder("Alice", "Bob");
list.stream()
    .filter(person -> "Alice".equals(person.getName()))
    .forEach(alice -> {
        assertThat(alice).extracting("size").isEqualTo("tall")
        assertThat(alice).extracting("hair").isEqualTo("brunette")
    });
list.stream()
    .filter(person -> "Bob".equals(person.getName()))
    .forEach(bob -> {
        assertThat(bob).extracting("size").isEqualTo("tiny")
        assertThat(bob).extracting("hair").isNull()
    });

or equivalently (java 7) :

assertThat(list).extracting("name").containsExactlyInAnyOrder("Alice", "Bob");
for(Person person : list){
    switch (testCase.getName()){
        case "Alice":
            assertThat(person).extracting("size").isEqualTo("tall")
            assertThat(person).extracting("hair").isEqualTo("brunette")
            break;
        case "Bob":
            assertThat(person).extracting("size").isEqualTo("tiny")
            assertThat(person).extracting("hair").isNull()
            break;
    }
}

but I am wondering if there is a better solution.

I like the fact that this solution makes a distinction between the expected elements being in the list and the elements themselves being correct.


Solution

  • For filtering, you can directly use any flavor of filteredOn, then either allMatch or allSatisfy (when I say directly I mean no need to stream your collection in order to filter it).

    I suggest to explore AssertJ API, you have other assertions like anySatisfy or using conditions with method like are, areAtLeast, ... the vast majority of the API has javadoc with examples to show how to use it.

    Additionally one can have a look at the examples in the assertj-examples project.

    Hope it helps