如何做类似 Assertions.assertAllFalse() 的事情?

How to do something like Assertions.assertAllFalse()?

我正在使用 import static org.junit.jupiter.api.Assertions.*; 进行单元测试,如果它们是错误的,我必须断言许多项目。例如:

boolean item1 = false;
boolean item2 = false;
boolean item3 = false;
boolean item4 = false;

// is something like this possible
Assertions.assertAllFalse(item1, item2, item3, item4);

我应该使用什么方法以及如何使用?

你可以使用 assertFalse(item1 || item2 || item3 || item4).

根据您的值的数量,最简单的(恕我直言)是将其简单地写成逻辑表达式:

Assertions.assertThat(item1 || item2 || item3 || item4).isFalse();
Assertions.assertThat(!(item1 && item2 && item3 && item4)).isTrue();

如果您的布尔值之一为真,测试将失败。

或者,如果您事先不知道值的数量,iterable and array assertions 可能会有帮助:

final List<Boolean> bools = …; // e.g. List.of(item1, item2, item3, item4)
Assertions.assertThat(bools).containsOnly(false);
Assertions.assertThat(bools).doesNotContain(true);
Assertions.assertThat(bools).allMatch(b -> !b);
Assertions.assertThat(bools).noneMatch(b -> b);

或者您甚至可以使用普通 Java 流来表达您的期望:

final List<Boolean> bools = …; // e.g. List.of(item1, item2, item3, item4)
Assertions.assertThat(bools.stream().filter(b -> b).count()).isEqualTo(0);
Assertions.assertThat(bools.stream().allMatch(b -> !b)).isTrue();

您可以为此实现自己的方法:

@Test
public void test(){
  assertAllFalse(true, true, false);
}

public void assertAllFalse(Boolean... conditions){
  List.of(conditions).forEach(Assert::assertFalse);
}