Skip to content

Instantly share code, notes, and snippets.

@XinyueZ
Forked from AniketSK/CoroutineTestRule.kt
Created October 16, 2019 22:18
Show Gist options
  • Save XinyueZ/deeb0a80c675c1be1b79cbb311175fc9 to your computer and use it in GitHub Desktop.
Save XinyueZ/deeb0a80c675c1be1b79cbb311175fc9 to your computer and use it in GitHub Desktop.
A test rule to allow testing coroutines that use the main dispatcher. Without this you'd run into "java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used"
......
dependencies {
def coroutinesVersion = "1.3.0-M1"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutinesVersion"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion"
testImplementation 'org.hamcrest:hamcrest-library:2.1'
testImplementation group: 'org.mockito', name: 'mockito-core', version: '2.25.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
testImplementation group: 'org.mockito', name: 'mockito-core', version: '2.25.0'
}
package com.aniketkadam.sharevideoshortcut
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
@ExperimentalCoroutinesApi
class CoroutineTestRule : TestRule {
override fun apply(base: Statement?, description: Description?): Statement =
object : Statement() {
override fun evaluate() {
Dispatchers.setMain(TestCoroutineDispatcher())
try {
base?.evaluate()
} finally {
Dispatchers.resetMain()
}
}
}
}
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.MockitoAnnotations
import org.mockito.Mockito.`when` as wh
@RunWith(JUnit4::class)
class ExampleTest {
@ExperimentalCoroutinesApi
@get:Rule
val coroutineTestRule = CoroutineTestRule()
@ExperimentalCoroutinesApi
@Test
fun exampleTest() = runBlockingTest {
val result = suspendingFunction()
assert(result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment