Reputation: 180
I'm using import static org.junit.jupiter.api.Assertions.*;
for unit testing and I have to assert for many items if they are false. For instance:
boolean item1 = false;
boolean item2 = false;
boolean item3 = false;
boolean item4 = false;
// is something like this possible
Assertions.assertAllFalse(item1, item2, item3, item4);
What method should I use and how?
Upvotes: 0
Views: 341
Reputation: 265817
Depending on the number of your values, easiest (IMHO) would be to simply write it out as a logical expression:
Assertions.assertThat(item1 || item2 || item3 || item4).isFalse();
Assertions.assertThat(!(item1 && item2 && item3 && item4)).isTrue();
If one of your boolean values is true, the test will fail.
Or, if you do not know the number of values beforehand, iterable and array assertions might be of help:
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);
Or you might even use plain Java streams to express your expectation:
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();
Upvotes: 2
Reputation: 3040
You could implement your own method for that:
@Test
public void test(){
assertAllFalse(true, true, false);
}
public void assertAllFalse(Boolean... conditions){
List.of(conditions).forEach(Assert::assertFalse);
}
Upvotes: 2