我正在使用AssertJ,我需要检查列表中的所有对象都具有intField > 0
。类似这样的东西:
assertThat(myObjectList).extracting(p -> p.getIntField()).isGreaterThan(0);
实现这一目标的正确方法是什么?我应该使用其他图书馆吗?
选项1:
使用allMatch(Predicate)
:
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>