android - MediatorLiveData源在测试期间不会更新

标签 android kotlin viewmodel android-livedata

我的 View 模型中有一个MediatorLiveData,应该对模型层的LiveData发射使用react,并在必要时采取措施并更新其侦听器。由于某些原因,源在测试期间不会更新。

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

模拟观察者和存储库方法似乎无济于事。永远不会调用doSomething(),并且currentState不会更新为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)
    }
}

即使将观察者除了直接放在调解器上的mockLiveData1mockLiveData2上,也不会导致在调解器中更新源。

最佳答案

如我的帖子中所示,我正在使用模拟LiveData作为调解器数据的源。这些应该只是LiveData实现。

@Before
fun setup() {
    liveData1 = MutableLiveData()
    whenever(mockRepository.getLiveData1()).thenReturn(liveData1)
    liveData1.postValue("initial value")
    myViewModel.state.observeForever(mockStateObserver)
}

关于android - MediatorLiveData源在测试期间不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54015043/

相关文章:

android - 如何在 React Native 0.60-RC 中生成签名的 apk

Android 可扩展列表为单个组设置背景颜色

android - 需要 bool 类型的值 : Popup Menu

c++ - "group by"代理模型

c# - 通过触发器更改列表框的数据模板时,WPF ViewModel 数据绑定(bind)不起作用

java - 如何在 Android 的 MVVM 中处理回调和状态

kotlin - 使用范围的稀疏值列表

android - Kotlin - 如何为 RecyclerVIew 实现 ItemClickListener

wpf - MVVM:设计具有聚合/依赖 ViewModel 的 ViewModel 架构

android - 从 Gallery 加载 ImageView 上的图片(图片来 self 的 Google Photos)