Android Architecture sample unit testing live data

Issue

@Test
fun sendResultToUI() {

    val foo  MutableLiveData<Resource<User>>()
    val bar  MutableLiveData<Resource<User>>()
    `when`(userRepository.loadUser("foo")).thenReturn(foo)
    `when`(userRepository.loadUser("bar")).thenReturn(bar)
    val observer  mock<Observer<Resource<User>>>()
    userViewModel.user.observeForever(observer) //Create foo and bar, observe user live data

    userViewModel.setLogin("foo")
    verify(observer, never()).onChanged(any()) //Make sure that setting login to foo did not touch vm.user?

    /*val fooUser  TestUtil.createUser("foo")
    val fooValue  Resource.success(fooUser)
    foo.value  fooValue
    verify(observer).onChanged(fooValue)
    reset(observer)

    val barUser  TestUtil.createUser("bar")
    val barValue  Resource.success(barUser)
    bar.value  barValue
    userViewModel.setLogin("bar")
    verify(observer).onChanged(barValue)*/
}

Can anyone please explain wtf this line: verify(observer, never()).onChanged(any()) is doing in Google’s GithubBrowser sample? I just don’t understand it, calling setLogin() fires the observer so how the hell can we verify that onChanged() was never called when we specifically triggered it on the previous line!?

Solution

calling setLogin() fires the observer

No, calling setLogin just return your a foo LiveData, the underlying value is not updated yet until you set it (foo.value fooValue). So this line tests onChange is not called if no value received.

Answered By – jaychang0917

Leave a Comment