1
+ package com.baeldung.intArrayToStringArray
2
+
3
+ import org.assertj.core.api.Assertions.assertThat
4
+ import org.junit.jupiter.api.Test
5
+ import org.junit.jupiter.api.assertThrows
6
+
7
+ class IntArrayToStringArrayUnitTest {
8
+
9
+ @Test
10
+ fun `when using toInt then it converts array` () {
11
+ val stringArray = arrayOf(" 1" , " 2" , " 3" , " 4" , " 5" )
12
+ val intArray = stringArray.map { it.toInt() }.toIntArray()
13
+ assertThat(intArray.all { it is Int }).isTrue()
14
+ assertThat(intArray).isEqualTo(arrayOf(1 ,2 ,3 ,4 ,5 ))
15
+ }
16
+
17
+ @Test
18
+ fun `when using toInt then exception is thrown` () {
19
+ val stringArray = arrayOf(" 1" , " 2" , " 3" , " four" , " 5" )
20
+ assertThrows<NumberFormatException > { stringArray.map { it.toInt() } }
21
+ }
22
+
23
+ @Test
24
+ fun `when using toInt then exception is handled` () {
25
+ val stringArray = arrayOf(" 1" , " 2" , " 3" , " four" , " 5" )
26
+ val intList = mutableListOf<Int >()
27
+ for (element in stringArray) {
28
+ try {
29
+ val intValue = element.toInt()
30
+ intList.add(intValue)
31
+ } catch (e: NumberFormatException ) {
32
+ // Handle the case when provided value is not a number
33
+ }
34
+ }
35
+ val intArray = intList.toIntArray()
36
+ assertThat(intArray).isEqualTo(arrayOf(1 ,2 ,3 ,5 ))
37
+ }
38
+
39
+ @Test
40
+ fun `when using toIntOrNull then it converts array` () {
41
+ val stringArray = arrayOf(" 1" , " 2" , " 3" , " four" , " 5" )
42
+ val intArray = stringArray.mapNotNull { it.toIntOrNull() }.toIntArray()
43
+ assertThat(intArray.all { it is Int }).isTrue()
44
+ assertThat(intArray).isEqualTo(arrayOf(1 ,2 ,3 ,5 ))
45
+ }
46
+ }
0 commit comments