Assertj验证集合中每个项的字段始终为null

时间:2017-03-09 10:53:48

标签: java assertj

我正在寻找一个解决方案来检查集合中的每个项目是否都有expectedNullField字段。

以下不起作用:

assertThat(aCollection).extracting("expectedNullField").isNull();

请注意,以下按预期方式工作: assertThat(aCollection).extracting("expectedNotNullField").isNotNull();

有人帮助我吗?

感谢。

2 个答案:

答案 0 :(得分:4)

如果您知道尺寸(让我们说它是3),您可以使用

assertThat(aCollection).extracting("expectedNullField")
                       .containsNull();

或者如果您只想检查是否存在空值

    assertThat(aCollection).extracting("expectedNullField")
                           .containsOnly(null);

请注意,您无法使用:

containsOnlyNullElements()

因为它含糊不清(containsOnly指定了varargs参数)。

我可以考虑在AssertJ中添加adb logcat .... Unable to instantiate application com.myfakeappname.MainApplication: java.lang.ClassNotFoundException: Didn't find class "com.myfakeappname.MainApplication" on path: DexPathList... .... 来克服上面的编译错误。

答案 1 :(得分:0)

您可以使用条件

Condition<YourClass> nullField = new Condition<>("expecting field to be null") {
  @Override
  public boolean matches(YourClass value) {
    return value.getField() == null;
  }
};

assertThat(aCollection).have(nullField);

可能比其他解决方案更容易阅读

assertThat(aCollection).filteredOn("expectedNullField", not(null)).isEmpty();