Skip to content

PartTests

Arnaud Giuliani edited this page Sep 27, 2018 · 7 revisions

Steps


Writing unit tests for Android ViewModel


1.1 - DetailViewModelMockTest

Let's update the corresponding unit tests.

  • Let's create the DetailViewModelMockTest from DetailPresenterMockTest
  • Your mocked view is now an Android Observer (android.arch.lifecycle.Observer) of State:
@Mock
lateinit var view: Observer<ViewModelState>
  • Rename your presenter property to viewModel and change its type to DetailViewModel

Let's update the before() function to setup your dependency:

  • Also make the view observe the ViewModel with observeForever function: viewModel.states.observeForever(view)
  • Uncomment the InstantTaskExecutorRule rule to allow LiveData execution in test

Now update the tests to check that view has been notified with an ArgumentCaptor:

// setup ArgumentCaptor
val arg = ArgumentCaptor.forClass(ViewModelState::class.java)
// Here we expect 2 calls on view.onChanged
verify(view, times(2)).onChanged(arg.capture())

val values = arg.allValues
// Test obtained values in order
assertEquals(2, values.size)
assertEquals(Loading, values[0])
assertEquals(DetailViewModel.DetailLoaded(weather), values[1])

1.2 - SplashViewModelMockTest

Update the corresponding tests in SplashViewModelMockTest.kt:

  • Create SplashViewModelMockTest from SplashPresenterMockTest class
  • Uncomment InstantTaskExecutorRule
  • Rename presenter property to viewModel
  • Change type of view property to Observer<ViewModelEvent>
  • Update before() function to observe your viewModel
  • Update the tests using ArgumentCaptor to check the returned events

1.3 - WeatherViewModelMockTest

Let's update our tests. From the WeatherHeaderPresenterMockTest class:

  • Delete WeatherListPresenterMockTest
  • Rename WeatherHeaderPresenterMockTest class to WeatherViewModelMockTest
  • Rename presenter property to viewModel
  • Change type of view property to Observer<ViewModelState>, and rename it statesView
  • Add a new view, eventsView of type Observer<ViewModelEvent>
  • Uncomment InstantTaskExecutorRule
  • Update before() function to observe with statesView and eventsView
  • Update the tests using ArgumentCaptor to check the returned states and events (look at the MockedData object which contains mocked data)

Clone this wiki locally