I have a MediatorLiveData
living in my viewmodel that is supposed to react to LiveData
emissions from the model layer, taking actions and updating its listeners when necessary. For some reason, the sources don't update during testing.
class MyViewModel(private val repository: Repository) : ViewModel() {
private val liveData1: LiveData<String> = repository.getString1()
private val livedata2: LiveData<String> = repository.getString2()
val currentState = MediatorLiveData<MyState>
init {
currentState.addSource(liveData1) {
it?.let { string1 ->
doSomething()
currentState.postValue(String1Updated)
}
}
currentState.addSource(liveData2) {
it?.let { string1 ->
doSomethingElse()
currentState.postValue(String2Updated)
}
}
}
}
Mocking an observer and the repository methods doesn't seem to help. doSomething()
is never called, and currentState is not updated to String1Updated.
@RunWith(MockitoJUnitRunner::class)
class MyViewModelTest {
@get:Rule instantTaskExecutorRule = InstantTaskExecutorRule()
@Mock lateinit var mockRepository: Repository
@Mock lateinit var mockLiveData1: MutableLiveData<String>
@Mock lateinit var mockLiveData2: MutableLiveData<String>
@Mock lateinit var mockStateObserver: Observer<MyState>
lateinit var myViewModel: MyViewModel
@Before
fun setup() {
whenever(mockRepository.getLiveData1()).thenReturn(mockLiveData1)
whenever(mockRepository.getLiveData2()).thenReturn(mockLiveData2)
myViewModel = myViewModel(mockRepository)
}
@Test
fun `Does something when live data 1 is updated`() {
myViewModel.state.observeForever(mockStateObserver)
mockLiveData1.postValue("hello world")
verify(mockStateObserver).onChanged(String1Updated)
}
}
Even placing observers directly on mockLiveData1
and mockLiveData2
in addition to the observer on the mediator does not cause the sources to be updated in the mediator.