Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssertJ on list of Optionals

Tags:

java

assertj

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 ?

like image 420
Emerson Cod Avatar asked Dec 07 '25 18:12

Emerson Cod


1 Answers

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())
);
like image 52
noiaverbale Avatar answered Dec 09 '25 12:12

noiaverbale