Skip to content

Instantly share code, notes, and snippets.

@titoaesj
Created May 24, 2023 11:28
Show Gist options
  • Save titoaesj/22870019bfce72602f143d7bd56657ab to your computer and use it in GitHub Desktop.
Save titoaesj/22870019bfce72602f143d7bd56657ab to your computer and use it in GitHub Desktop.
Android Unit Tests Rule
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()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment