Skip to content

Commit 3082337

Browse files
committed
Improve the error message for when the Main dispatcher is missing
1 parent efd4264 commit 3082337

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

kotlinx-coroutines-test/jvm/src/internal/TestMainDispatcherJvm.kt

+25-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,21 @@ internal class TestMainDispatcherFactory : MainDispatcherFactory {
1010
val secondBestFactory = otherFactories.maxByOrNull { it.loadPriority } ?: MissingMainCoroutineDispatcherFactory
1111
/* Do not immediately create the alternative dispatcher, as with `SUPPORT_MISSING` set to `false`,
1212
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+
})
1428
}
1529

1630
/**
@@ -26,3 +40,13 @@ internal actual fun Dispatchers.getTestMainDispatcher(): TestMainDispatcher {
2640
require(mainDispatcher is TestMainDispatcher) { "TestMainDispatcher is not set as main dispatcher, have $mainDispatcher instead." }
2741
return mainDispatcher
2842
}
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

Comments
 (0)