Skip to content

Instantly share code, notes, and snippets.

@samiuelson
Created April 4, 2020 11:20
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 samiuelson/9186d68fc2ab0caf2a1fe9dba885bac3 to your computer and use it in GitHub Desktop.
Save samiuelson/9186d68fc2ab0caf2a1fe9dba885bac3 to your computer and use it in GitHub Desktop.
Coroutines setup with org.jetbrains.kotlinx:kotlinx-coroutines-test
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
}
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