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