选项列表上的 AssertJ

我有一个可选列表,List<Optional<String>> optionals我喜欢用assertj它来断言几件事。

但我没能正确地做到这一点——我只在单个 Optional 上找到示例。

当然我可以自己做所有的检查,比如

Assertions.assertThat(s).allMatch(s1 -> s1.isPresent() && s1.get().equals("foo"));

并链接那些,但我仍然有一种感觉,通过 api 有一种更聪明的方式。

List<Optional<T>>我在这里错过了什么,还是在 assertj中没有支持?


HUX布斯
浏览 102回答 2
2回答

拉莫斯之舞

AssertJ 似乎没有为可选集合提供实用程序,但您可以迭代您的列表并对每个项目执行您的断言。list.forEach(element -> assertThat(element)&nbsp; &nbsp; &nbsp; &nbsp; .isPresent()&nbsp; &nbsp; &nbsp; &nbsp; .hasValue("something"));一种可能更好的方法是收集所有断言,而不是停留在第一个断言上。你可以用SoftAssertions不同的方式使用,但我更喜欢这个:SoftAssertions.assertSoftly(softly ->&nbsp; &nbsp; list.forEach(element -> softly.assertThat(element).isPresent()));

守着一只汪

assertThat(list).allSatisfy(o&nbsp;->&nbsp;assertThat(o).hasValue("something")));爪哇文档: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)验证实际的 Optional 是否包含一个值,并将该值提供给给定的 Consumer 以进行进一步的断言。应该用作对包含对象进行更深入断言的方式,作为对值的进一步要求。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java