3

I want to unit-test the sequence of a LiveData's results. I have a result LiveData which emits values when loading, success, or error. I want to test it to ensure that loading value is emitted first, then the success or error value.

is there a way to do this?

Amr Salah
  • 85
  • 9

1 Answers1

2

Yes, it's possible, I'll include an example which is using the mockk library. Let's say that you have a ViewModel and a LiveData<Your_type_here> result. You have to add a mocked observer (androidx.lifecycle.Observer) which values will be verified. In your test you'll have a class-level variable

@MockK
lateinit var observer: Observer<Your_type_here>

Then in the @Before (or if you have only one test, you can paste it there) function you should add this

viewModel.result.observeForever(observer)
every { observer.onChanged(any()) } just Runs

And in the test you'll have something like

// given - your mocking calls here
// when 
viewModel.doSomethingAndPostLiveDataResult()
// then
verifySequence {
    observer.onChanged(Your_type_here)
    observer.onChanged(Something_else)
}
PineapplePie
  • 816
  • 2
  • 13
  • Thank you. Is there an equivalent of verifySequence in Mockito? – Amr Salah Jul 24 '22 at 15:05
  • 1
    @AmrSalah as far as I remember, they have InOrder class for such cases. Haven't used Mockito for a while, but here is a big useful thread about it https://stackoverflow.com/a/21901415/19580355 – PineapplePie Jul 24 '22 at 15:09