MainDispatcherRule

class MainDispatcherRule(val testDispatcher: TestDispatcher = UnconfinedTestDispatcher()) : TestWatcher(source)

Swaps Dispatchers.Main for a TestDispatcher for the duration of a test.

Anything that launches into viewModelScope — including the updateStateWith and updateWith helpers in :core:ui — dispatches to Dispatchers.Main, which has no implementation under a plain JVM unit test. Without this rule those tests fail with Module with the Main dispatcher had failed to initialize.

Defaults to UnconfinedTestDispatcher so coroutines run eagerly and assertions can follow the call directly. Pass a StandardTestDispatcher when a test needs to control ordering itself.

Usage

class MyViewModelTest {
@get:Rule
val mainDispatcherRule = MainDispatcherRule()

@Test
fun `does the thing`() = runTest { /* ... */}
}

Parameters

testDispatcher

The dispatcher to install as Main.

Constructors

Link copied to clipboard
constructor(testDispatcher: TestDispatcher = UnconfinedTestDispatcher())

Properties

Link copied to clipboard
val testDispatcher: TestDispatcher