Skip to content

Instantly share code, notes, and snippets.

@marcellogalhardo
Last active July 7, 2021 12:06
Show Gist options
  • Save marcellogalhardo/3fc1517d5606cd4305b3266c34523939 to your computer and use it in GitHub Desktop.
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.
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