How to write unit test code for polling with Coroutine Job?

Viewed 31

I am using polling for an API call.

private var pollingJob: Job? = null

fun myApi(){
   pollingJob?.cancel()

   pollingJob = viewModelScope.launch{
       while(true){
           val result = apiRepo.callApi()
           _myResult.postValue(result)
           delay(30000L)
       }
   }
}

It seems like, I can't test this method because of looping. Is there any better way to be able to test it?

I think,

  1. It would be okay if I can test only calling it once and the value is set correctly.

maybe I can cancel polling job after calling it once. And also, here _isLoading, is set two times in one loop. How can I check it? 2. Polling test, check if the method calls the api at the right time repeatably.

How can I test it?

Maybe, I might use Timer or something else to call the next apis. But, Is there any better way?

0 Answers
Related