MainDispatcherRule

class MainDispatcherRule(dispatcher: TestDispatcher = UnconfinedTestDispatcher()) : TestWatcher

JUnit rule that swaps the Main dispatcher for a TestDispatcher for the duration of a test.

Why: ViewModels backed by viewModelScope.launch { … } schedule on Dispatchers.Main.immediate, which throws on the JVM without an installed dispatcher. UnconfinedTestDispatcher is the default because it runs coroutines eagerly in-thread, which makes MutableStateFlow updates from init { } blocks observable synchronously from the test body — no runTest { advanceUntilIdle() } gymnastics required for the common case.

Tests that need controlled virtual time (e.g. exercising delay(…) inside the SUT) should pass a StandardTestDispatcher() explicitly and drive the scheduler with runTest { … }.

Constructors

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

Functions

Link copied to clipboard
open override fun apply(p0: Statement, p1: Description): Statement