title: Android unit testing view model that receives flow
body: <p>I have a ViewModel that talks to a use case and gets a flow back i.e <code>Flow&lt;MyResult&gt;</code>. I want to unit test my ViewModel. I am new to using the flow. Need help pls. Here is the viewModel below - </p>
  
  <pre><code>class MyViewModel(private val handle: SavedStateHandle, private val useCase: MyUseCase) : ViewModel() {
  
          private val viewState = MyViewState()
  
          fun onOptionsSelected() =
              useCase.getListOfChocolates(MyAction.GetChocolateList).map {
                  when (it) {
                      is MyResult.Loading -&gt; viewState.copy(loading = true)
                      is MyResult.ChocolateList -&gt; viewState.copy(loading = false, data = it.choclateList)
                      is MyResult.Error -&gt; viewState.copy(loading = false, error = "Error")
                  }
              }.asLiveData(Dispatchers.Default + viewModelScope.coroutineContext)
  </code></pre>
  
  <p>MyViewState looks like this -</p>
  
  <pre><code> data class MyViewState(
          val loading: Boolean = false,
          val data: List&lt;ChocolateModel&gt; = emptyList(),
          val error: String? = null
      )
  </code></pre>
  
  <p>The unit test looks like below. The assert fails always don't know what I am doing wrong there.</p>
  
  <pre><code>class MyViewModelTest {
  
      @get:Rule
      val instantExecutorRule = InstantTaskExecutorRule()
  
      private val mainThreadSurrogate = newSingleThreadContext("UI thread")
  
      private lateinit var myViewModel: MyViewModel
  
      @Mock
      private lateinit var useCase: MyUseCase
  
      @Mock
      private lateinit var handle: SavedStateHandle
  
      @Mock
      private lateinit var chocolateList: List&lt;ChocolateModel&gt;
  
      private lateinit var viewState: MyViewState
  
  
      @Before
      fun setup() {
          MockitoAnnotations.initMocks(this)
          Dispatchers.setMain(mainThreadSurrogate)
          viewState = MyViewState()
          myViewModel = MyViewModel(handle, useCase)
      }
  
      @After
      fun tearDown() {
          Dispatchers.resetMain() // reset main dispatcher to the original Main dispatcher
          mainThreadSurrogate.close()
      }
  
      @Test
      fun onOptionsSelected() {
          runBlocking {
              val flow = flow {
                  emit(MyResult.Loading)
                  emit(MyResult.ChocolateList(chocolateList))
              }
  
              Mockito.`when`(useCase.getListOfChocolates(MyAction.GetChocolateList)).thenReturn(flow)
              myViewModel.onOptionsSelected().observeForever {}
  
              viewState.copy(loading = true)
              assertEquals(viewState.loading, true)
  
              viewState.copy(loading = false, data = chocolateList)
              assertEquals(viewState.data.isEmpty(), false)
              assertEquals(viewState.loading, true)
          }
      }
  }
  </code></pre>