1
+ package com.baeldung.printAllElementsInOneLine
2
+
3
+ import org.junit.jupiter.api.AfterEach
4
+ import org.junit.jupiter.api.BeforeEach
5
+ import org.junit.jupiter.api.Test
6
+ import java.io.ByteArrayOutputStream
7
+ import java.io.PrintStream
8
+ import kotlin.test.assertEquals
9
+
10
+
11
+ class PrintAllElementsInOneLineUnitTest {
12
+ val myArray = arrayOf(" A" , " B" , " C" , " D" , " E" , " F" )
13
+ val arrayWithComma = arrayOf(" A" , " B, C" , " D, E" , " F" )
14
+
15
+ val newLine = System .lineSeparator()
16
+ val stdOut = System .out
17
+ val myOutput = ByteArrayOutputStream ()
18
+
19
+ @BeforeEach
20
+ fun setup () {
21
+ System .setOut(PrintStream (myOutput))
22
+ }
23
+
24
+ @AfterEach
25
+ fun restore () {
26
+ System .setOut(stdOut)
27
+ }
28
+
29
+
30
+ @Test
31
+ fun `when using myOutput then we can verify println() result` () {
32
+ println (" Hello, world" )
33
+ assertEquals(" Hello, world$newLine " , myOutput.toString())
34
+
35
+ myOutput.reset()
36
+
37
+ println (" Kotlin rocks" )
38
+ assertEquals(" Kotlin rocks$newLine " , myOutput.toString())
39
+ }
40
+
41
+ @Test
42
+ fun `when converting array to list then all elements are in one line` () {
43
+ println (myArray.asList())
44
+ assertEquals(" [A, B, C, D, E, F]$newLine " , myOutput.toString())
45
+
46
+ myOutput.reset()
47
+
48
+ println (arrayWithComma.asList())
49
+ // cannot customize the output format
50
+ assertEquals(" [A, B, C, D, E, F]$newLine " , myOutput.toString())
51
+ }
52
+
53
+
54
+ @Test
55
+ fun `when using print() then get the expected result` () {
56
+ myArray.forEachIndexed { idx, e ->
57
+ print (if (idx == myArray.lastIndex) " $e$newLine " else " $e , " )
58
+ }
59
+ assertEquals(" A, B, C, D, E, F$newLine " , myOutput.toString())
60
+
61
+ myOutput.reset()
62
+
63
+ arrayWithComma.forEachIndexed { idx, e ->
64
+ print (if (idx == arrayWithComma.lastIndex) """ "$e "$newLine """ else """ "$e ", """ )
65
+ }
66
+ assertEquals(""" "A", "B, C", "D, E", "F"$newLine """ , myOutput.toString())
67
+ }
68
+
69
+ @Test
70
+ fun `when using joinToString() then get the expected result` () {
71
+ println (myArray.joinToString { it })
72
+ assertEquals(" A, B, C, D, E, F$newLine " , myOutput.toString())
73
+
74
+ myOutput.reset()
75
+
76
+ println (arrayWithComma.joinToString { """ "$it """" })
77
+ assertEquals(""" "A", "B, C", "D, E", "F"$newLine """ , myOutput.toString())
78
+ }
79
+
80
+ }
0 commit comments