简体   繁体   中英

AssertJ on list of Optionals

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 ?

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())
);
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM