对集合的所有元素断言相同的条件
Assert same condition on all elements of a collection
我正在使用 AssertJ,我需要检查列表中的所有对象是否都具有 intField > 0
。像这样:
assertThat(myObjectList).extracting(p -> p.getIntField()).isGreaterThan(0);
实现此目标的正确方法是什么?我应该使用其他库吗?
选项 1:
assertThat(asList(0, 2, 3))
.allMatch(i -> i > 0);
选项 2(由 Jens Schauder 建议):
将基于 Consumer<E>
的断言与 allSatisfy
结合使用:
assertThat(asList(0, 1, 2, 3))
.allSatisfy(i ->
assertThat(i).isGreaterThan(0));
第二个选项可能会导致更多信息失败消息。
在这种特殊情况下,消息突出显示某些元素预计 大于 0
java.lang.AssertionError:
Expecting all elements of:
<[0, 1, 2, 3]>
to satisfy given requirements, but these elements did not:
<0>
Expecting:
<0>
to be greater than:
<0>
我正在使用 AssertJ,我需要检查列表中的所有对象是否都具有 intField > 0
。像这样:
assertThat(myObjectList).extracting(p -> p.getIntField()).isGreaterThan(0);
实现此目标的正确方法是什么?我应该使用其他库吗?
选项 1:
assertThat(asList(0, 2, 3))
.allMatch(i -> i > 0);
选项 2(由 Jens Schauder 建议):
将基于 Consumer<E>
的断言与 allSatisfy
结合使用:
assertThat(asList(0, 1, 2, 3))
.allSatisfy(i ->
assertThat(i).isGreaterThan(0));
第二个选项可能会导致更多信息失败消息。
在这种特殊情况下,消息突出显示某些元素预计 大于 0
java.lang.AssertionError:
Expecting all elements of:
<[0, 1, 2, 3]>
to satisfy given requirements, but these elements did not:
<0>
Expecting:
<0>
to be greater than:
<0>