Reputation: 2090
I have a List of Optionals, like List<Optional<String>> optionals
and I like to use assertj
on it to assert several things.
But I fail to do this properly - I only find examples on a single Optional.
Of course I can do all checks by myself like
Assertions.assertThat(s).allMatch(s1 -> s1.isPresent() && s1.get().equals("foo"));
and chain those, but I still have the feeling, that there is a more smart way via the api.
Do I miss something here or is there no support for List<Optional<T>>
in assertj ?
Upvotes: 3
Views: 1816
Reputation: 808
assertThat(list).allSatisfy(o -> assertThat(o).hasValue("something")));
Javadoc :
For List<Optional<T>>
, see also : https://www.javadoc.io/doc/org.assertj/assertj-core/latest/org/assertj/core/api/AbstractOptionalAssert.html#hasValueSatisfying(java.util.function.Consumer)
Verifies that the actual Optional contains a value and gives this value to the given Consumer for further assertions. Should be used as a way of deeper asserting on the containing object, as further requirement(s) for the value.
Upvotes: 0
Reputation: 1678
AssertJ doesn't seems to provide utils for collections of optionals, but you can iterate your list and perform your assertions on every item.
list.forEach(element -> assertThat(element)
.isPresent()
.hasValue("something"));
A maybe better approach is to collect all your assertions instead of stopping at the first one. You can use SoftAssertions
in different ways, but I prefer this one:
SoftAssertions.assertSoftly(softly ->
list.forEach(element -> softly.assertThat(element).isPresent())
);
Upvotes: 3