Search code examples
androidunit-testingtestingandroid-livedataandroid-architecture-components

Unit Testing the SEQUENCE of values emitted from a single livedata


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?


Solution

  • 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)
    }