-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathTestDispatchersTest.kt
100 lines (85 loc) · 2.72 KB
/
TestDispatchersTest.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.test
import kotlinx.coroutines.*
import kotlinx.coroutines.test.internal.*
import kotlin.coroutines.*
import kotlin.test.*
class TestDispatchersTest: OrderedExecutionTestBase() {
@BeforeTest
fun setUp() {
Dispatchers.setMain(StandardTestDispatcher())
}
@AfterTest
fun tearDown() {
Dispatchers.resetMain()
}
/** Tests that asynchronous execution of tests does not happen concurrently with [AfterTest] (in fact, it does). */
@Ignore // fails on JS.
@Test
fun testMainMocking() = runTest {
val mainAtStart = mainTestDispatcher
assertNotNull(mainAtStart)
withContext(Dispatchers.Main) {
delay(10)
}
withContext(Dispatchers.Default) {
delay(10)
}
withContext(Dispatchers.Main) {
delay(10)
}
assertSame(mainAtStart, mainTestDispatcher)
}
/** Tests that the mocked [Dispatchers.Main] correctly forwards [Delay] methods. */
@Test
fun testMockedMainImplementsDelay() = runTest {
val main = Dispatchers.Main
withContext(main) {
delay(10)
}
withContext(Dispatchers.Default) {
delay(10)
}
withContext(main) {
delay(10)
}
}
/** Tests that [Distpachers.setMain] fails when called with [Dispatchers.Main]. */
@Test
fun testSelfSet() {
assertFailsWith<IllegalArgumentException> { Dispatchers.setMain(Dispatchers.Main) }
}
@Test
fun testImmediateDispatcher() = runTest {
Dispatchers.setMain(ImmediateDispatcher())
expect(1)
withContext(Dispatchers.Main) {
expect(3)
}
Dispatchers.setMain(RegularDispatcher())
withContext(Dispatchers.Main) {
expect(6)
}
finish(7)
}
private inner class ImmediateDispatcher : CoroutineDispatcher() {
override fun isDispatchNeeded(context: CoroutineContext): Boolean {
expect(2)
return false
}
override fun dispatch(context: CoroutineContext, block: Runnable) = throw RuntimeException("Shouldn't be reached")
}
private inner class RegularDispatcher : CoroutineDispatcher() {
override fun isDispatchNeeded(context: CoroutineContext): Boolean {
expect(4)
return true
}
override fun dispatch(context: CoroutineContext, block: Runnable) {
expect(5)
block.run()
}
}
}
private val mainTestDispatcher get() = ((Dispatchers.Main as? TestMainDispatcher)?.delegate as? TestDispatcher)