首页 > 解决方案 > 如何执行 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);

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

标签: javaunit-testingjunitassertion

解决方案


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

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

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

或者,如果您事先不知道值的数量,可迭代和数组断言可能会有所帮助:

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();

推荐阅读