Skip to content

Commit 06df055

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

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

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

Lines changed: 25 additions & 1 deletion
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+
}

ui/kotlinx-coroutines-android/android-unit-tests/test/ordered/tests/FirstMockedMainTest.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ open class FirstMockedMainTest : TestBase() {
3535
component.launchSomething()
3636
throw component.caughtException
3737
} catch (e: IllegalStateException) {
38-
assertTrue(e.message!!.contains("Dispatchers.setMain from kotlinx-coroutines-test"))
38+
assertTrue(e.message!!.contains("Dispatchers.setMain"))
3939
}
4040
}
4141
}

0 commit comments

Comments
 (0)