@@ -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
/* *
@@ -140,7 +142,10 @@ public fun TestCoroutineScope(context: CoroutineContext = EmptyCoroutineContext)
140
142
*
141
143
* It ensures that all the test module machinery is properly initialized.
142
144
* * If [context] doesn't define a [TestCoroutineScheduler] for orchestrating the virtual time used for delay-skipping,
143
- * a new one is created, unless a [TestDispatcher] is provided, in which case [TestDispatcher.scheduler] is used.
145
+ * a new one is created, unless either
146
+ * - a [TestDispatcher] is provided, in which case [TestDispatcher.scheduler] is used;
147
+ * - at the moment of the creation of the scope, [Dispatchers.Main] is delegated to a [TestDispatcher], in which case
148
+ * its [TestCoroutineScheduler] is used.
144
149
* * If [context] doesn't have a [ContinuationInterceptor], a [StandardTestDispatcher] is created.
145
150
* * A [CoroutineExceptionHandler] is created that makes [TestCoroutineScope.cleanupTestCoroutines] throw if there were
146
151
* any uncaught exceptions, or forwards the exceptions further in a platform-specific manner if the cleanup was
@@ -173,7 +178,9 @@ public fun createTestCoroutineScope(context: CoroutineContext = EmptyCoroutineCo
173
178
dispatcher
174
179
}
175
180
null -> {
176
- scheduler = context[TestCoroutineScheduler ] ? : TestCoroutineScheduler ()
181
+ val mainDispatcherScheduler =
182
+ ((Dispatchers .Main as ? TestMainDispatcher )?.delegate as ? TestDispatcher )?.scheduler
183
+ scheduler = context[TestCoroutineScheduler ] ? : mainDispatcherScheduler ? : TestCoroutineScheduler ()
177
184
StandardTestDispatcher (scheduler)
178
185
}
179
186
else -> throw IllegalArgumentException (" Dispatcher must implement TestDispatcher: $dispatcher " )
0 commit comments