Last active
July 7, 2021 12:06
-
-
Save marcellogalhardo/3fc1517d5606cd4305b3266c34523939 to your computer and use it in GitHub Desktop.
A test rule to allow testing coroutines with ease. It provides you a `scope: TestCoroutineScope` and `dispatcher: TestCoroutineDispatcher` ready to be used.
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.test.TestCoroutineDispatcher | |
import kotlinx.coroutines.test.TestCoroutineScope | |
import kotlinx.coroutines.test.resetMain | |
import kotlinx.coroutines.test.setMain | |
import org.junit.rules.TestWatcher | |
import org.junit.runner.Description | |
@Suppress("MemberVisibilityCanBePrivate") | |
class CoroutineRule( | |
val dispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher(), | |
val scope: TestCoroutineScope = TestCoroutineScope(dispatcher), | |
) : TestWatcher() { | |
override fun starting(description: Description?) { | |
super.starting(description) | |
Dispatchers.setMain(dispatcher) | |
} | |
override fun finished(description: Description?) { | |
super.finished(description) | |
Dispatchers.resetMain() | |
dispatcher.cleanupTestCoroutines() | |
scope.cleanupTestCoroutines() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment