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.