@@ -10,7 +10,21 @@ internal class TestMainDispatcherFactory : MainDispatcherFactory {
10
10
val secondBestFactory = otherFactories.maxByOrNull { it.loadPriority } ? : MissingMainCoroutineDispatcherFactory
11
11
/* Do not immediately create the alternative dispatcher, as with `SUPPORT_MISSING` set to `false`,
12
12
it will throw an exception. Instead, create it lazily. */
13
- return TestMainDispatcher ({ secondBestFactory.tryCreateDispatcher(otherFactories) })
13
+ return TestMainDispatcher ({
14
+ val dispatcher = try {
15
+ secondBestFactory.tryCreateDispatcher(otherFactories)
16
+ } catch (e: Throwable ) {
17
+ reportMissingMainCoroutineDispatcher(e)
18
+ }
19
+ if (dispatcher.isMissing()) {
20
+ reportMissingMainCoroutineDispatcher(runCatching {
21
+ // attempt to dispatch something to the missing dispatcher to trigger the exception.
22
+ dispatcher.dispatch(dispatcher, Runnable { })
23
+ }.exceptionOrNull()) // can not be null, but it does not matter.
24
+ } else {
25
+ dispatcher
26
+ }
27
+ })
14
28
}
15
29
16
30
/* *
@@ -26,3 +40,13 @@ internal actual fun Dispatchers.getTestMainDispatcher(): TestMainDispatcher {
26
40
require(mainDispatcher is TestMainDispatcher ) { " TestMainDispatcher is not set as main dispatcher, have $mainDispatcher instead." }
27
41
return mainDispatcher
28
42
}
43
+
44
+ private fun reportMissingMainCoroutineDispatcher (e : Throwable ? = null): Nothing {
45
+ throw IllegalStateException (
46
+ " Dispatchers.Main was accessed when the platform dispatcher was absent " +
47
+ " and the test dispatcher was unset. Please make sure that Dispatchers.setMain() is called " +
48
+ " before accessing Dispatchers.Main and that Dispatchers.Main is not accessed after " +
49
+ " Dispatchers.resetMain()." ,
50
+ e
51
+ )
52
+ }
0 commit comments