如何执行Assert.assertallfalse()之类的操作?

sigwle7e  于 2021-06-29  发布在  Java
关注(0)|答案(3)|浏览(279)

我在用 import static org.junit.jupiter.api.Assertions.*; 对于单元测试,我必须为许多项Assert它们是否为false。例如:

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

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

我应该用什么方法,怎么用?

jei2mxaa

jei2mxaa1#

您可以实现自己的方法:

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

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

sycxhyv72#

根据值的数量,最简单的方法(imho)是将其作为逻辑表达式写出:

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

如果布尔值之一为真,测试将失败。
或者,如果您事先不知道值的数目,iterable和arrayAssert可能会有所帮助:

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

voase2hg3#

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

相关问题