gpt4 book ai didi

android - 单元测试使用 ViewModelScope.launch 调用具有延迟的挂起函数的 ViewModel 方法

转载 作者:行者123 更新时间:2023-12-03 21:01:38 29 4
gpt4 key购买 nike

在我的 ViewModel我有一个 onTextChanged通过 EditText 上的数据绑定(bind)调用的方法.在那里我使用viewModelScope.launch{}开始 suspend功能。在那个函数中,我延迟了 500 毫秒。现在我如何测试 onTextChanged方法?我尝试的一切总是在延迟完成之前完成测试。我试过 runBlockingTest , TestCoroutineDispatcherrunBlocking .

文本观察者:

override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
searchJob = if (searchJob?.isActive == true) {
searchJob?.cancel()
viewModelScope.launch { search(s.toString()) }
} else {
viewModelScope.launch { search(s.toString()) }
}
}

搜索方法:
 private suspend fun search(query: String) {
delay(500)
searchUseCase(SearchParams(query)).fold({

}, {

})
}

考试:
    @Test
fun `Search is fired after 500ms when text is changed`() = runBlockingTest {
val viewModel = ViewModel(useCase)
viewModel.onTextChanged("test", 0, 0, 0)

//TODO assert time was 500ms or more

//This fails
coVerify(exactly = 1) { useCase.invoke(any()) }
}

最佳答案

谷歌推荐的是,你应该以某种方式注入(inject) CoroutineDispatcher到您的 View 模型,以便您可以在测试期间更改它。

class MainViewModel(
private val dispatcher: CoroutineDispatcher = Dispatchers.Default
) : ViewModel() {

private var _userData: MutableLiveData<Any> = MutableLiveData<Any>()
val userData: LiveData<Any> = _userData

fun savedDelayed() = viewModelScope.launch {
delay(1000)
saveSessionData()
}

suspend fun saveSessionData() {
viewModelScope.launch(dispatcher) {
_userData.value = "some_user_data"
}
}
}

@ExperimentalCoroutinesApi
class MainViewModelTest {

private val testDispatcher = TestCoroutineDispatcher()

@ExperimentalCoroutinesApi
@get:Rule
var mainCoroutineRule = MainCoroutineRule()

@get:Rule
var instantExecutorRule = InstantTaskExecutorRule()

@Test
fun testsSaveSessionData() = runBlockingTest {
val mainViewModel = MainViewModel(testDispatcher)

mainViewModel.savedDelayed()
testDispatcher.advanceUntilIdle()

val userData = mainViewModel.userData.value
assertEquals("some_user_data", userData)
}

}
代码粘贴自中篇文章,并针对您的用例进行了修改。请阅读文章以获得进一步的解释:
https://medium.com/swlh/unit-testing-with-kotlin-coroutines-the-android-way-19289838d257

关于android - 单元测试使用 ViewModelScope.launch 调用具有延迟的挂起函数的 ViewModel 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56966375/

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