java - 如何执行 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);
我应该使用什么方法以及如何使用?
解决方案
根据您的值的数量,最简单的(恕我直言)是将其简单地写为逻辑表达式:
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();
推荐阅读
- google-cloud-platform - Google Compute Engine(容器)上的连接被拒绝
- android - 如何在 Android Studio 中同时水平滚动多个 TextView?
- android-webview - Appium Start Inspector Session webview 菜单栏区域无法点击选择元素
- flutter - setState() 会影响 Flutter 的性能吗?
- python - Dockerfile 中的 PYTHONUNBUFFERED 有什么作用?
- woocommerce - Woocommerce“wc-template-functions.php”文件中的致命错误
- java - 循环内发生数据库错误时如何回滚整个过程?
- android - 我在使用 firebase 时遇到问题,我正在尝试获取一个列表,但即使有值,该列表也不会显示在我的回收视图中
- sql-server - 如何使用 Nifi 将 Azure DataLakeStorage 中的 .parquet 数据转储到 Microsoft SQL Server 数据库?
- javascript - 是否应该在节点中收听 http.ClientReuqest 的“错误”事件?