AssertJ in the optional list
I
have an optional list like List<Optional<String>> optionals
I like to assert several things on it with assertj
.
But I failed to do it properly – I only found examples on a single optional.
Of course I can do all the checks myself
Assertions.assertThat(s).allMatch(s1 -> s1.isPresent() && s1.get().equals("foo"));
And link them up, but I still feel that there is a smarter approach through the API.
What am I missing here or is List<Optional<T>>
in assertj?
Solution
AssertJ doesn’t seem to provide utilities for optional collections, but you can iterate over the list and perform assertions on each item.
list.forEach(element -> assertThat(element) .isPresent() .hasValue("something"));
Perhaps a better approach is to collect all the assertions instead of stopping at the first assertion. You can use SoftAssertions
in different ways, but I prefer this one :
SoftAssertions.assertSoftly(softly -> list.forEach(element -> softly.assertThat(element).isPresent()) );