Skip to content

Instantly share code, notes, and snippets.

@titoaesj
Created May 24, 2023 11:28
Show Gist options
  • Select an option

  • Save titoaesj/22870019bfce72602f143d7bd56657ab to your computer and use it in GitHub Desktop.

Select an option

Save titoaesj/22870019bfce72602f143d7bd56657ab to your computer and use it in GitHub Desktop.

Revisions

  1. titoaesj created this gist May 24, 2023.
    28 changes: 28 additions & 0 deletions MainDispatcherRule.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    import kotlinx.coroutines.Dispatchers
    import kotlinx.coroutines.ExperimentalCoroutinesApi
    import kotlinx.coroutines.test.TestDispatcher
    import kotlinx.coroutines.test.UnconfinedTestDispatcher
    import kotlinx.coroutines.test.resetMain
    import kotlinx.coroutines.test.setMain
    import org.junit.rules.TestRule
    import org.junit.rules.TestWatcher
    import org.junit.runner.Description

    /**
    * A JUnit [TestRule] that sets the Main dispatcher to [testDispatcher]
    * for the duration of the test.
    */
    @ExperimentalCoroutinesApi
    class MainDispatcherRule(
    private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher()
    ) : TestWatcher() {
    override fun starting(description: Description) {
    super.starting(description)
    Dispatchers.setMain(testDispatcher)
    }

    override fun finished(description: Description) {
    super.finished(description)
    Dispatchers.resetMain()
    }
    }