Skip to content

Why do we need a Dispatcher as a rule to test coroutines

Devrath edited this page Jul 11, 2021 · 3 revisions

Description

  • Dispatchers are not available for the test and androidTest packages so when testing the live data. There might be a possibility of failure.
  • Dispatchers rely upon the Main looper and available only during the execution of production code.
  • So we need to define a rule to handle the live data.

Code

@ExperimentalCoroutinesApi class MainCoroutineRule( private val dispatcher: CoroutineDispatcher = 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() } 

}

  • Here in the starting(..) method we replace our main dispatcher with the test dispatcher.
  • In the finished(..) method before we complete we clean up the co-routines if any are running and replace the test dispatcher again with the main dispatcher.
  • Usage of the rule
@ExperimentalCoroutinesApi class ShoppingViewModelTest { @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() @get:Rule var mainCoroutineRule = MainCoroutineRule() @Test fun `someTestCase`() { // Test case  } }
  • Rule will apply to all the test cases
Clone this wiki locally