Created
April 20, 2020 09:57
-
-
Save akueisara/39ffce97c1db6d5e1c6be37f0aca9018 to your computer and use it in GitHub Desktop.
Testing Coroutines on Android
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.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() | |
} | |
} |
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
@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