Created
May 12, 2021 18:27
-
-
Save NinoDLC/0a9f58f9345b109d216bd8714f007470 to your computer and use it in GitHub Desktop.
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