Android Architecture sample unit testing live data


fun sendResultToUI() {

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

    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

    val barUser  TestUtil.createUser("bar")
    val barValue  Resource.success(barUser)
    bar.value  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!?


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