Skip to content

Instantly share code, notes, and snippets.

@NinoDLC
Created January 10, 2022 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NinoDLC/a7fdd1c58dac93222af009a3753f2a17 to your computer and use it in GitHub Desktop.
Save NinoDLC/a7fdd1c58dac93222af009a3753f2a17 to your computer and use it in GitHub Desktop.
TestCoroutineRule.kt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.*
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
@ExperimentalCoroutinesApi
class TestCoroutineRule : TestRule {
val testCoroutineDispatcher = UnconfinedTestDispatcher()
val testCoroutineScope = TestScope(testCoroutineDispatcher)
override fun apply(base: Statement, description: Description?) = object : Statement() {
@Throws(Throwable::class)
override fun evaluate() {
Dispatchers.setMain(testCoroutineDispatcher)
base.evaluate()
Dispatchers.resetMain() // reset main dispatcher to the original Main dispatcher
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment