Skip to content

Instantly share code, notes, and snippets.

@akueisara
Created April 20, 2020 09:57
Show Gist options
  • Save akueisara/39ffce97c1db6d5e1c6be37f0aca9018 to your computer and use it in GitHub Desktop.
Save akueisara/39ffce97c1db6d5e1c6be37f0aca9018 to your computer and use it in GitHub Desktop.
Testing Coroutines on Android
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.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description
/* JUnit rule: https://junit.org/junit4/javadoc/4.12/org/junit/Rule.html */
@ExperimentalCoroutinesApi
class MainCoroutineRule(val dispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()):
TestWatcher(),
TestCoroutineScope by TestCoroutineScope(dispatcher) {
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.setMain(dispatcher)
}
override fun finished(description: Description?) {
super.finished(description)
cleanupTestCoroutines()
Dispatchers.resetMain()
}
}
@ExperimentalCoroutinesApi
//@RunWith(AndroidJUnit4::class) // androidXTestExtKotlinRunner
class TasksViewModelTest {
// REPLACE start
val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()
@Before
fun setupDispatcher() {
Dispatchers.setMain(testDispatcher)
}
@After
fun tearDownDispatcher() {
Dispatchers.resetMain()
testDispatcher.cleanupTestCoroutines()
}
// REPLACE end
// WITH start
@get:Rule
var mainCoroutineRule = MainCoroutineRule()
// WITH end
@Before
fun setupViewModel() {
// Code to setup viewmodel ...
}
@Test
fun Test1() {
// coroutine task ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment