简体   繁体   中英

Kotlin Coroutine ViewModel UnitTesting does not cover viewmodel


I am facing issues in passing Coroutine UnitTestcase for ViewModel. I am using MVVM retrofit.
Though I mocked the result, its displaying result as "null"
Please find below UnitTest case 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)



}


Please find viewmodel method to be tested:

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


}


When tried to run unittest, I see the control is returned after executing the below line in ViewModel without running through other code though data is mocked:
val response = apiService.fetchUserPosts()

Please help me in resolving this issue.
I am using mockito framework

Because retroCoroutineViewModel is not using the mocked apiService instance.

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 your service (pass apiService via constructor to RetroCoroutineViewModel?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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