1

我查看了 AssertJ 示例(https://github.com/joel-costigliola/assertj-examples/blob/master/assertions-examples/src/test/java/org/assertj/examples/IterableAssertionsExamples.java)但是我找不到以下示例:-

  1. 断言列表的大小为 X 例如3
  2. 断言所有项目都是null

例如

List<String> items= Arrays.asList(null, null, null);
assertThat(items).hasSize(3).containsOnlyNulls();

注意 -containsOnlyNulls不存在,但这本质上是我想要测试的。这可以在 AssertJ 中实现吗?

4

1 回答 1

6

你可以使用

// need to cast to String
assertThat(items).hasSize(3).containsOnly((String) null);

或者

assertThat(items).filteredOn(item -> item == null).hasSize(3);

- 编辑 -

containsOnlyNulls断言已在 3.9.0+ 中添加到 AssertJ

例子:

// assertion will pass
Iterable<String> items = Arrays.asList(null, null, null);
assertThat(items).containsOnlyNulls();

// assertion will fail because items2 contains a not null element
Iterable<String> items2 = Arrays.asList(null, null, "notNull");
assertThat(items2).containsOnlyNulls();

// assertion will fail since an empty iterable does not contain any elements and therefore no null ones.
Iterable<String> empty = new ArrayList<>();
assertThat(empty).containsOnlyNulls(); 
于 2017-08-21T21:50:51.193 回答