对集合的所有元素断言相同的条件

问题描述 投票:0回答:1

我正在使用 AssertJ,我需要检查列表中的所有对象是否都有

intField > 0
。像这样的东西:

assertThat(myObjectList).extracting(p -> p.getIntField()).isGreaterThan(0);

实现这一目标的正确方法是什么?我应该使用其他库吗?

java unit-testing assertj
1个回答
25
投票

选项1

使用

allMatch(Predicate)

assertThat(asList(0, 1, 2, 3))
    .allMatch(i -> i > 0);
java.lang.AssertionError: 
Expecting all elements of:
  [0, 1, 2, 3]
to match given predicate but this element did not:
  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
error: 
Expecting actual:
  0
to be greater than:
  0
© www.soinside.com 2019 - 2024. All rights reserved.