MVVM with Coroutine Flow and Unit Tests in Kotlin — Part 2

1.Before you begin:

The link to the part 1 is given below:


  • Familiarity with the Architecture Components ViewModel, LiveData, Repository.
  • Experience with Kotlin syntax, including lambdas.
  • Familiarity with Mockito and JUnit testing Framework

What you’ll do ?

Use Mockito testing framework to unit test ViewModel in developed app .

Getting Setup :

The code is available in the above Github repository.

git clone

Unit Testing Concepts:


A JUnit Test Rule that swaps the background executor used by the Architecture Components with a different one which executes each task synchronously.

You can use this rule for your host side tests that use Architecture Components which means when writing unit tests for view model this rule instantly returns the asynchronous task like connecting with Network and so on. It is needed to test code with LiveData.


It sets the main dispatcher to testCoroutineDispatcher, runs the test then resets and cleanup. It also creates testCoroutineScope in which we can run our tests.

val testInstantTaskExecutorRule: TestRule = InstantTaskExecutorRule()

val testCoroutineRule = TestCoroutineRule()

Mocking :

We mock the required classes of ViewModel using @mock annotation.

private lateinit var apiHelper: EmployeeService

private lateinit var employeeRepository: EmployeeRepository

Unit Test a method in ViewModel:

private val testDispatcher = TestCoroutineDispatcher()
fun test_fetchEmployeeList() = testDispatcher.runBlockingTest {
var data = UserModel.Data(
var ad = UserModel.Support("StatusCode Weekly","",)
var list = arrayListOf<UserModel.Data>()
var retroResponse = UserModel(list,2,6,ad,12,12)
val employeeViewModel = EmployeeViewModel(testDispatcher,employeeRepository)
val response = Response.success(retroResponse)
val channel = Channel<Response<UserModel>>()
val flow = channel.consumeAsFlow()
Mockito.`when`(employeeRepository.fetchEmployees()).thenReturn(flow )

launch {
Assert.assertEquals(false, employeeViewModel.fetchLoadStatus()?.value)

In the above created a Dummy model class and created a flow out of it which repository returns after it communicates with Network.

Since we mocked the repository class, we will return the created flow with below code sample:

Mockito.`when`(employeeRepository.fetchEmployees()).thenReturn(flow )

We initialize viewmodel with mocked Repository class.

val employeeViewModel = EmployeeViewModel(testDispatcher,employeeRepository)

We verify the value of the mocked response when view model method is called



In these two blogs, we have covered Coroutines with Flows in MVVM Architecture with unit tests with a simple app.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store