繁体   English   中英

Kotlin Coroutine ViewModel UnitTesting 不涵盖 viewmodel

[英]Kotlin Coroutine ViewModel UnitTesting does not cover viewmodel


我在为 ViewModel 传递协程 UnitTestcase 时遇到问题。 我正在使用 MVVM retrofit。
虽然我嘲笑了结果,但它的显示结果为“null”
请在下面找到 UnitTest 案例 class:

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

    }

}

视图模型工厂:

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 响应 = apiService.fetchUserPosts()

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

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

The object of viewmodel is being created and the apiService is being mocked (considering the ifs are being executed) but the apiService object in retroCoroutineViewModel object is different than the mocked instance so you need to make sure that the retroCoroutineViewModel object has the mocked apiService object of您的服务(通过构造函数将apiService传递给 RetroCoroutineViewModel?)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM