@@ -6,6 +6,8 @@ package kotlinx.coroutines.test
6
6
7
7
import kotlinx.coroutines.*
8
8
import kotlinx.coroutines.internal.*
9
+ import kotlinx.coroutines.test.internal.*
10
+ import kotlinx.coroutines.test.internal.TestMainDispatcher
9
11
import kotlin.coroutines.*
10
12
11
13
/* *
@@ -135,7 +137,10 @@ public fun TestCoroutineScope(context: CoroutineContext = EmptyCoroutineContext)
135
137
*
136
138
* It ensures that all the test module machinery is properly initialized.
137
139
* * If [context] doesn't define a [TestCoroutineScheduler] for orchestrating the virtual time used for delay-skipping,
138
- * a new one is created, unless a [TestDispatcher] is provided, in which case [TestDispatcher.scheduler] is used.
140
+ * a new one is created, unless either
141
+ * - a [TestDispatcher] is provided, in which case [TestDispatcher.scheduler] is used;
142
+ * - at the moment of the creation of the scope, [Dispatchers.Main] is delegated to a [TestDispatcher], in which case
143
+ * its [TestCoroutineScheduler] is used.
139
144
* * If [context] doesn't have a [ContinuationInterceptor], a [StandardTestDispatcher] is created.
140
145
* * A [CoroutineExceptionHandler] is created that makes [TestCoroutineScope.cleanupTestCoroutines] throw if there were
141
146
* any uncaught exceptions, or forwards the exceptions further in a platform-specific manner if the cleanup was
@@ -168,7 +173,9 @@ public fun createTestCoroutineScope(context: CoroutineContext = EmptyCoroutineCo
168
173
dispatcher
169
174
}
170
175
null -> {
171
- scheduler = context[TestCoroutineScheduler ] ? : TestCoroutineScheduler ()
176
+ val mainDispatcherScheduler =
177
+ ((Dispatchers .Main as ? TestMainDispatcher )?.delegate as ? TestDispatcher )?.scheduler
178
+ scheduler = context[TestCoroutineScheduler ] ? : mainDispatcherScheduler ? : TestCoroutineScheduler ()
172
179
StandardTestDispatcher (scheduler)
173
180
}
174
181
else -> throw IllegalArgumentException (" Dispatcher must implement TestDispatcher: $dispatcher " )
0 commit comments