Hey folks, I've been having a bit of trouble with...
# coroutines
m
Hey folks, I've been having a bit of trouble with testing and I'm wondering if any of you know the cause. Currently we have this in our VM:
Copy code
public val channel: LiveData<Channel> = channelState.channelData.combine(channelState.members) { _, _ ->
        channelState.toChannel()
    }.asLiveData()
We do in fact know that this does work when the app is run, but want to write a simple test to ensure this doesn't break in the future.
Copy code
@OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun `When channel members update should update channel`() = runBlockingTest {
        val messageListHeaderViewModel = MessageListHeaderViewModel(CID, chatClient = chatClient)
        val mockObserver: Observer<Channel> = spy()
        messageListHeaderViewModel.channel.observeForever(mockObserver)

        val memberList = createMembers { createMember(User(name = "user")) }
        membersMock.emit(memberList)
        advanceUntilIdle()

        verify(mockObserver, times(2)).onChanged(any())
    }
The issue is that the observer will update only once which is the first emission of
Channel
triggered by
SharingStarted.Eagerly
. Curiously enough, if you collect the Flow in tests without the
.asLiveData()
transformation, you will collect all of it including the latest update. However then transforming to
LiveData
no interactions with the mock can be observed. Even more curiously the same
.asLiveData()
transformed variable is testable if no
combine
is called. So if we just had
channelState.members.asLiveData()
we could observe all of the emissions from it without any issue. I've been trying to wrap my head around this for a while and can't understand what gives. Thanks in advance for any assistance 😄
t
I think it's related to the fact that unlike Flow, updates to the value of a LiveData are only notified on Android's main thread. Unit Tests are not run on the main thread by default. You may need to use
InstantTaskExecutorRule
when testing code using
LiveData
.