Created
April 4, 2020 11:20
-
-
Save samiuelson/9186d68fc2ab0caf2a1fe9dba885bac3 to your computer and use it in GitHub Desktop.
Coroutines setup with org.jetbrains.kotlinx:kotlinx-coroutines-test
This file contains 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
class MyUnitTest { | |
@get:Rule | |
val coroutineRule = TestCoroutineRule() | |
@Test | |
fun `my test executed on TestCoroutineDispatcher`() = coroutineRule.runBlockingTest { | |
assertEquals(42, answer()) | |
} | |
} | |
suspend fun answer(): Int { | |
delay(TimeUnit.DAYS.toMillis(Long.MAX_VALUE)) | |
return 42 | |
} | |
This file contains 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.* | |
import org.junit.rules.TestRule | |
import org.junit.runner.Description | |
import org.junit.runners.model.Statement | |
@ExperimentalCoroutinesApi | |
class TestCoroutineRule : TestRule { | |
private val testCoroutineDispatcher = TestCoroutineDispatcher() | |
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() | |
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