Skip to content

Commit

Permalink
Improve the error message for when the Main dispatcher is missing
Browse files Browse the repository at this point in the history
  • Loading branch information
dkhalanskyjb committed Dec 17, 2024
1 parent efd4264 commit 06df055
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,21 @@ internal class TestMainDispatcherFactory : MainDispatcherFactory {
val secondBestFactory = otherFactories.maxByOrNull { it.loadPriority } ?: MissingMainCoroutineDispatcherFactory
/* Do not immediately create the alternative dispatcher, as with `SUPPORT_MISSING` set to `false`,
it will throw an exception. Instead, create it lazily. */
return TestMainDispatcher({ secondBestFactory.tryCreateDispatcher(otherFactories) })
return TestMainDispatcher({
val dispatcher = try {
secondBestFactory.tryCreateDispatcher(otherFactories)
} catch (e: Throwable) {
reportMissingMainCoroutineDispatcher(e)
}
if (dispatcher.isMissing()) {
reportMissingMainCoroutineDispatcher(runCatching {
// attempt to dispatch something to the missing dispatcher to trigger the exception.
dispatcher.dispatch(dispatcher, Runnable { })
}.exceptionOrNull()) // can not be null, but it does not matter.
} else {
dispatcher
}
})
}

/**
Expand All @@ -26,3 +40,13 @@ internal actual fun Dispatchers.getTestMainDispatcher(): TestMainDispatcher {
require(mainDispatcher is TestMainDispatcher) { "TestMainDispatcher is not set as main dispatcher, have $mainDispatcher instead." }
return mainDispatcher
}

private fun reportMissingMainCoroutineDispatcher(e: Throwable? = null): Nothing {
throw IllegalStateException(
"Dispatchers.Main was accessed when the platform dispatcher was absent " +
"and the test dispatcher was unset. Please make sure that Dispatchers.setMain() is called " +
"before accessing Dispatchers.Main and that Dispatchers.Main is not accessed after " +
"Dispatchers.resetMain().",
e
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ open class FirstMockedMainTest : TestBase() {
component.launchSomething()
throw component.caughtException
} catch (e: IllegalStateException) {
assertTrue(e.message!!.contains("Dispatchers.setMain from kotlinx-coroutines-test"))
assertTrue(e.message!!.contains("Dispatchers.setMain"))
}
}
}

0 comments on commit 06df055

Please sign in to comment.