简体   繁体   中英

How to test a method in viewModel which returns LiveData value from repository

In my ViewModel I am calling a method from my repository class which returns a LiveData from a webservice. My viewModel code:

class MainViewModel @Inject constructor(val mainRepository: MainRepository) : ViewModel() {
   val source: LiveData<My_Result> = mainRepository.fetchApiresultFromClient(str_query)  
       .......... }

My question is that is there a way to get real data from the webservice called in repository or do I just prepare the result and assert that its not null; something like below:

when(mainrepository.fetchApiresultFromClient(any(String::class))).thenReturn(myPreparedLiveData<My_result>)

As the question is tagged as unit-testing, IMHO, expecting real data from a web service does not actually fall into the scope of unit-testing. You might call than an integration testing, however, from the unit-testing point of view, you might consider mocking the response from the function that calls the web service and verify if the method was called using proper arguments that you expect.

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