Skip to content

Commit f8e6535

Browse files
authored
Added code sample and unit tests for any, none and all methods (#812)
1 parent 2165121 commit f8e6535

File tree

1 file changed

+85
-0
lines changed
  • core-kotlin-modules/core-kotlin-collections-5/src/test/kotlin/com/baeldung/anyNoneAll

1 file changed

+85
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package com.baeldung.anyNoneAll
2+
3+
import org.junit.Test
4+
import kotlin.test.assertFalse
5+
import kotlin.test.assertTrue
6+
7+
class AnyNoneAllUnitTest {
8+
@Test
9+
fun `check if no element matches the condition using none`() {
10+
val numbers = listOf(1, 2, 3, 4, 5)
11+
val noZeroes = numbers.none { it == 0 }
12+
assertTrue(noZeroes)
13+
}
14+
15+
@Test
16+
fun `none on empty list returns true`() {
17+
val numbers: List<Int> = listOf()
18+
val noZeroes = numbers.none { it == 0 }
19+
assertTrue(noZeroes)
20+
}
21+
22+
@Test
23+
fun `check if atleast one element matches the condition using any`() {
24+
val numbers = listOf(1, 2, 3, 4, 5, 6)
25+
val hasEven = numbers.any { it % 2 == 0 }
26+
assertTrue(hasEven)
27+
}
28+
29+
@Test
30+
fun `return false if no element matches predicate in any`() {
31+
val numbers = listOf(1, 2, 3, 4, 5, 6)
32+
val has100plus = numbers.any { it > 100 }
33+
assertFalse(has100plus)
34+
}
35+
36+
@Test
37+
fun `any on empty list returns false`() {
38+
val numbers: List<Int> = listOf()
39+
val hasAnyZeroes = numbers.any { it == 0 }
40+
assertFalse(hasAnyZeroes)
41+
}
42+
43+
@Test
44+
fun `check if all elements matches predicate in all`() {
45+
val numbers = listOf(1, 2, 3, 4, 5, 6)
46+
val allPositive = numbers.all { it > 0 }
47+
assertTrue(allPositive)
48+
}
49+
50+
@Test
51+
fun `return false if atleast one doesnt match predicate in all`() {
52+
val numbers = listOf(1, 2, 3, 4, 5, 6)
53+
val noMultipleOf5 = numbers.all { it % 5 != 0 }
54+
assertFalse(noMultipleOf5)
55+
}
56+
57+
@Test
58+
fun `all on empty list returns true (Vacuous truth)`() {
59+
val numbers: List<Int> = listOf()
60+
val hasAnyZeroes = numbers.all { it != 0 }
61+
assertTrue(hasAnyZeroes)
62+
}
63+
64+
@Test
65+
fun `check handling of null elements in any`() {
66+
val numbers = listOf(1, 2, null, 4, 5)
67+
val hasNull = numbers.any { it == null }
68+
assertTrue(hasNull)
69+
}
70+
71+
@Test
72+
fun `check handling of null elements in none`() {
73+
val numbers = listOf(1, 2, null, 4, 5)
74+
val hasNull = numbers.none { it == null }
75+
assertFalse(hasNull)
76+
}
77+
78+
@Test
79+
fun `check handling of null elements in all`() {
80+
val numbers: List<Int?> = listOf(null, null, null)
81+
val allNull = numbers.all { it == null }
82+
assertTrue(allNull)
83+
}
84+
85+
}

0 commit comments

Comments
 (0)