我在为ViewModel传递Coroutine UnitTestcase时遇到问题。我正在使用MVVM改造。
尽管我 mock 了该结果,但其显示结果为“null”
请在下面的UnitTest案例类中找到:

val testDispatcher = TestCoroutineDispatcher()
@Test
fun `check viewmodel fetches data correctly`() = testDispatcher.runBlockingTest{
    var retroRxModel = RetroRxModel("tile", "body", "1")
    var retroRXModelList = ArrayList<RetroRxModel>()
    retroRXModelList.add(retroRxModel)
    response = Response.success(retroRXModelList)
    retroCoroutineViewModel = RetroCoroutineViewModel(testDispatcher)
    if (retrofit != null) {

        if (apiService != null) {
            Mockito.`when`(apiService.fetchUserPosts()).thenReturn(response)
        }
    }
    retroCoroutineViewModel.fetchResponseFromAPI()
    println("Loading Val::::${retroCoroutineViewModel.fetchLoadStatus()?.value}")
    println("PostLive Dat::::${retroCoroutineViewModel.fetchPostLiveData().value}")
    Assert.assertEquals(true,retroCoroutineViewModel.loading?.value)



}

请找到要测试的viewmodel方法:
fun fetchResponseFromAPI(){
    viewModelScope.launch (dispatcher){
       // postsMutableLiveData.postValue(null)
        try{

            val response  = apiService.fetchUserPosts()
            if(response.isSuccessful){
                postsMutableLiveData.postValue(response.body())
                loading.postValue(false)
               // loading.value = false
            }else{
                loading.postValue(false)
                errorOnAPI.postValue("Something went wrong::${response.message()}")
            }



        }catch (e:Exception){
            loading.postValue(false)
            errorOnAPI.postValue("Something went wrong::${e.localizedMessage}")
        }

    }

}

ViewModelFactory:
class RetroCoroutineViewModelFactory : ViewModelProvider.Factory {
@ExperimentalStdlibApi
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
    if (modelClass.isAssignableFrom(RetroCoroutineViewModel::class.java)) {
        return RetroCoroutineViewModel(Dispatchers.Main) as T
    }
    throw IllegalArgumentException("Unknown ViewModel class")
}


}

尝试运行unittest时,我看到在ViewModel中执行以下行后,尽管模拟了数据,但未运行其他代码,但返回了控件:
val response = apiService.fetchUserPosts()

请帮我解决这个问题。我正在使用Mockito框架

最佳答案

因为retroCoroutineViewModel没有使用模拟的apiService实例。

正在创建viewmodel对象并且正在模拟apiService(考虑是否正在执行ifs),但是apiService对象中的retroCoroutineViewModel对象与模拟实例不同,因此您需要确保retroCoroutineViewModel对象具有模拟的apiService对象。您的服务(通过构造函数将apiService传递给RetroCoroutineViewModel吗?)

07-27 16:49