1
+ package com.baeldung.booleanValueOfKotlinEquivalent
2
+
3
+ import org.junit.jupiter.api.Assertions.assertEquals
4
+ import org.junit.jupiter.api.Assertions.assertThrows
5
+ import org.junit.jupiter.api.Test
6
+
7
+ class BooleanValueOfKotlinEquivalentUnitTest {
8
+
9
+ @Test
10
+ fun `obtain equivalent in Kotlin by string comparison using equals method` () {
11
+ assertEquals(true , convertStringToBoolean(" true" ))
12
+ assertEquals(true , convertStringToBoolean(" TRUE" ))
13
+ assertEquals(false , convertStringToBoolean(" false" ))
14
+ }
15
+
16
+ @Test
17
+ fun `obtain equivalent in Kotlin using toBoolean method` () {
18
+ assertEquals(true , " true" .toBoolean())
19
+ assertEquals(true , " TRUE" .toBoolean())
20
+ assertEquals(false , " false" .toBoolean())
21
+ }
22
+
23
+ @Test
24
+ fun `obtain equivalent in Kotlin using toBooleanStrictOrNull method` () {
25
+ var str: String? = " fjdfj"
26
+ assertEquals(true , " true" .toBooleanStrictOrNull())
27
+ assertEquals(null , str?.toBooleanStrictOrNull())
28
+ assertEquals(false , " false" .toBooleanStrictOrNull())
29
+ }
30
+
31
+ @Test
32
+ fun `obtain equivalent in Kotlin using toBooleanStrict method` () {
33
+ assertEquals(true , " true" .toBooleanStrict())
34
+ assertEquals(false , " false" .toBooleanStrict())
35
+ assertThrows(IllegalArgumentException ::class .java) {
36
+ " TRUE" .toBooleanStrict()
37
+ }
38
+ }
39
+
40
+ @Test
41
+ fun `obtain equivalent in Kotlin using parseBoolean method` () {
42
+ assertEquals(true , java.lang.Boolean .parseBoolean(" true" ))
43
+ assertEquals(true , java.lang.Boolean .parseBoolean(" TRUE" ))
44
+ assertEquals(false , java.lang.Boolean .parseBoolean(" false" ))
45
+ }
46
+
47
+ @Test
48
+ fun `obtain equivalent in Kotlin using valueOf method` () {
49
+ assertEquals(true , java.lang.Boolean .valueOf(" true" ))
50
+ assertEquals(true , java.lang.Boolean .valueOf(" TRUE" ))
51
+ assertEquals(false , java.lang.Boolean .valueOf(" false" ))
52
+ }
53
+
54
+ @Test
55
+ fun `obtain equivalent in Kotlin using custom extension function` () {
56
+ assertEquals(true , " true" .toBooleanValue())
57
+ assertEquals(true , " TRUE" .toBooleanValue())
58
+ assertEquals(false , " false" .toBooleanValue())
59
+ }
60
+
61
+ @Test
62
+ fun `obtain equivalent in Kotlin using regex` () {
63
+ assertEquals(true , convertStringToBooleanUsingRegex(" true" ))
64
+ assertEquals(true , convertStringToBooleanUsingRegex(" TRUE" ))
65
+ assertEquals(false , convertStringToBooleanUsingRegex(" false" ))
66
+ }
67
+
68
+ }
69
+ fun convertStringToBoolean (input : String ): Boolean {
70
+ return if (input.equals(" true" , ignoreCase = true )) true else false
71
+ }
72
+
73
+ fun convertStringToBooleanUsingRegex (input : String ): Boolean {
74
+ return input.trim().matches(" ^(?i:true)$" .toRegex())
75
+ }
76
+
77
+ fun String.toBooleanValue (): Boolean =
78
+ when (this .toLowerCase()) {
79
+ " true" -> true
80
+ else -> false
81
+ }
0 commit comments