Skip to content

Commit f177ac4

Browse files
naoussinappy29
andauthored
KTLN-576 Create a List from Kotlin Flow (#1166)
* added unit test * code changes * code fixes * code fixes --------- Co-authored-by: nappy29 <[email protected]>
1 parent e014838 commit f177ac4

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.baeldung.flowToList
2+
3+
import kotlinx.coroutines.flow.*
4+
import kotlinx.coroutines.test.runTest
5+
import org.junit.jupiter.api.Assertions.assertEquals
6+
import org.junit.jupiter.api.Test
7+
import java.util.concurrent.CopyOnWriteArrayList
8+
9+
class FlowToListUnitTest {
10+
11+
@Test
12+
fun `create list from flow using toList method`() = runTest {
13+
val flow = flowOf(1, 2, 3)
14+
val result = flow.toList()
15+
16+
assertEquals(listOf(1, 2, 3), result)
17+
}
18+
19+
@Test
20+
fun `create list using toList with custom mutable list`() = runTest {
21+
val flow = flowOf(1, 2, 3)
22+
val result = CopyOnWriteArrayList<Int>()
23+
flow.toList(result)
24+
25+
assertEquals(listOf(1, 2, 3), result)
26+
}
27+
28+
@Test
29+
fun `create list from flow using collect method`() = runTest {
30+
val flow = flowOf(1, 2, 3)
31+
val result = mutableListOf<Int>()
32+
flow.collect { result.add(it) }
33+
34+
assertEquals(listOf(1, 2, 3), result)
35+
}
36+
37+
@Test
38+
fun `create list from flow using fold method`() = runTest {
39+
val flow = flowOf(1, 2, 3)
40+
val result = flow.fold(mutableListOf<Int>()) { acc, value ->
41+
acc.apply { add(value) }
42+
}
43+
assertEquals(listOf(1, 2, 3), result)
44+
}
45+
46+
}

0 commit comments

Comments
 (0)