• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download

<lambda>null1 package kotlinx.coroutines.test
2 
3 import kotlinx.coroutines.testing.*
4 import kotlinx.coroutines.*
5 import kotlinx.coroutines.flow.*
6 import kotlin.test.*
7 
8 class StandardTestDispatcherTest: OrderedExecutionTestBase() {
9 
10     private val scope = TestScope(StandardTestDispatcher())
11 
12     @BeforeTest
13     fun init() {
14         scope.asSpecificImplementation().enter()
15     }
16 
17     @AfterTest
18     fun cleanup() {
19         scope.runCurrent()
20         assertEquals(listOf(), scope.asSpecificImplementation().legacyLeave())
21     }
22 
23     /** Tests that the [StandardTestDispatcher] follows an execution order similar to `runBlocking`. */
24     @Test
25     fun testFlowsNotSkippingValues() = scope.launch {
26         // https://github.com/Kotlin/kotlinx.coroutines/issues/1626#issuecomment-554632852
27         val list = flowOf(1).onStart { emit(0) }
28             .combine(flowOf("A")) { int, str -> "$str$int" }
29             .toList()
30         assertEquals(list, listOf("A0", "A1"))
31     }.void()
32 
33     /** Tests that each [launch] gets dispatched. */
34     @Test
35     fun testLaunchDispatched() = scope.launch {
36         expect(1)
37         launch {
38             expect(3)
39         }
40         finish(2)
41     }.void()
42 
43     /** Tests that dispatching is done in a predictable order and [yield] puts this task at the end of the queue. */
44     @Test
45     fun testYield() = scope.launch {
46         expect(1)
47         scope.launch {
48             expect(3)
49             yield()
50             expect(6)
51         }
52         scope.launch {
53             expect(4)
54             yield()
55             finish(7)
56         }
57         expect(2)
58         yield()
59         expect(5)
60     }.void()
61 
62     /** Tests that the [TestCoroutineScheduler] used for [Dispatchers.Main] gets used by default. */
63     @Test
64     fun testSchedulerReuse() {
65         val dispatcher1 = StandardTestDispatcher()
66         Dispatchers.setMain(dispatcher1)
67         try {
68             val dispatcher2 = StandardTestDispatcher()
69             assertSame(dispatcher1.scheduler, dispatcher2.scheduler)
70         } finally {
71             Dispatchers.resetMain()
72         }
73     }
74 
75 }
76