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