Created
May 24, 2023 11:28
-
-
Save titoaesj/22870019bfce72602f143d7bd56657ab to your computer and use it in GitHub Desktop.
Android Unit Tests Rule
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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