gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:08:48 24 4
gpt4 key购买 nike

我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com