可选列表中的 AssertJ
AssertJ on list of Optionals
我有一个可选列表,比如 List<Optional<String>> optionals
,我喜欢在上面使用 assertj
来断言几件事。
但我没能正确地做到这一点 - 我只在一个可选的上找到示例。
当然我可以自己做所有检查,比如
Assertions.assertThat(s).allMatch(s1 -> s1.isPresent() && s1.get().equals("foo"));
并将它们链接起来,但我仍然觉得,通过 api 有一种更聪明的方法。
我是不是漏掉了什么,或者不支持 List<Optional<T>>
in assertj?
AssertJ 似乎没有为可选集合提供实用程序,但您可以迭代列表并对每个项目执行断言。
list.forEach(element -> assertThat(element)
.isPresent()
.hasValue("something"));
也许更好的方法是收集所有断言,而不是停在第一个断言处。你可以用不同的方式使用 SoftAssertions
,但我更喜欢这个:
SoftAssertions.assertSoftly(softly ->
list.forEach(element -> softly.assertThat(element).isPresent())
);
assertThat(list).allSatisfy(o -> assertThat(o).hasValue("something")));
Java文档:
- https://www.javadoc.io/doc/org.assertj/assertj-core/latest/org/assertj/core/api/AbstractIterableAssert.html#allSatisfy(java.util.function.Consumer)
- https://www.javadoc.io/doc/org.assertj/assertj-core/latest/org/assertj/core/api/AbstractOptionalAssert.html#hasValue(VALUE)
对于 List<Optional<T>>
,另请参阅: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.
我有一个可选列表,比如 List<Optional<String>> optionals
,我喜欢在上面使用 assertj
来断言几件事。
但我没能正确地做到这一点 - 我只在一个可选的上找到示例。
当然我可以自己做所有检查,比如
Assertions.assertThat(s).allMatch(s1 -> s1.isPresent() && s1.get().equals("foo"));
并将它们链接起来,但我仍然觉得,通过 api 有一种更聪明的方法。
我是不是漏掉了什么,或者不支持 List<Optional<T>>
in assertj?
AssertJ 似乎没有为可选集合提供实用程序,但您可以迭代列表并对每个项目执行断言。
list.forEach(element -> assertThat(element)
.isPresent()
.hasValue("something"));
也许更好的方法是收集所有断言,而不是停在第一个断言处。你可以用不同的方式使用 SoftAssertions
,但我更喜欢这个:
SoftAssertions.assertSoftly(softly ->
list.forEach(element -> softly.assertThat(element).isPresent())
);
assertThat(list).allSatisfy(o -> assertThat(o).hasValue("something")));
Java文档:
- https://www.javadoc.io/doc/org.assertj/assertj-core/latest/org/assertj/core/api/AbstractIterableAssert.html#allSatisfy(java.util.function.Consumer)
- https://www.javadoc.io/doc/org.assertj/assertj-core/latest/org/assertj/core/api/AbstractOptionalAssert.html#hasValue(VALUE)
对于 List<Optional<T>>
,另请参阅: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.