Created
December 28, 2021 18:28
-
-
Save NinoDLC/06c8b60a391bdcfe3d240c284b91aea5 to your computer and use it in GitHub Desktop.
TestCoroutineRule.kt
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.TestCoroutineDispatcher | |
import kotlinx.coroutines.test.TestCoroutineScope | |
import kotlinx.coroutines.test.resetMain | |
import kotlinx.coroutines.test.runBlockingTest | |
import kotlinx.coroutines.test.setMain | |
import org.junit.rules.TestRule | |
import org.junit.runner.Description | |
import org.junit.runners.model.Statement | |
@ExperimentalCoroutinesApi | |
class TestCoroutineRule : TestRule { | |
val testCoroutineDispatcher = TestCoroutineDispatcher() | |
private val testCoroutineScope = TestCoroutineScope(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 | |
testCoroutineScope.cleanupTestCoroutines() | |
} | |
} | |
fun runBlockingTest(block: suspend TestCoroutineScope.() -> Unit) = | |
testCoroutineScope.runBlockingTest { block() } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment