MainDispatcherRule
class MainDispatcherRule(val dispatcher: TestDispatcher = StandardTestDispatcher()) : TestWatcher(source)
A JUnit 4 rule that replaces Dispatchers.Main with dispatcher for each test and always restores it afterward, including when the test fails.
Pass rule.dispatcher to runTest so the code under test and the test share one scheduler:
@get:Rule val mainDispatcher = MainDispatcherRule()
@Test fun loads() = runTest(mainDispatcher.dispatcher) { ... }Content copied to clipboard