Skip to content

Boiler plate code to make threading work on the coroutines in the mockK

Devrath edited this page Jun 26, 2021 · 2 revisions

Add the below lines in each of the test class

@ExperimentalCoroutinesApi @get:Rule val coroutineTestRule = CoroutinesTestRule() @get:Rule val instantTaskExecutorRule = InstantTaskExecutorRule()

Define the below class

/**  * Sets the main coroutines dispatcher for unit testing.  *  * See https://medium.com/androiddevelopers/easy-coroutines-in-android-viewmodelscope-25bffb605471  * and https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-test  */ @ExperimentalCoroutinesApi class CoroutinesTestRule( val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher() ) : TestWatcher() { override fun starting(description: Description?) { super.starting(description) Dispatchers.setMain(testDispatcher) } override fun finished(description: Description?) { super.finished(description) Dispatchers.resetMain() testDispatcher.cleanupTestCoroutines() } }
Clone this wiki locally