...

/

Testing Android Functions That Launch Coroutines

Testing Android Functions That Launch Coroutines

Learn how to test Android functions that launch coroutines and how to set a test dispatcher with a rule.

We typically start coroutines on ViewModels, Presenters, Fragments, or Activities on Android. These are fundamental classes, and we should test them. Think of the MainViewModel implementation below.

Press + to interact
class MainViewModel(
private val userRepo: UserRepository,
private val newsRepo: NewsRepository,
) : BaseViewModel() {
private val _userName: MutableLiveData<String> =
MutableLiveData()
val userName: LiveData<String> = _userName
private val _news: MutableLiveData<List<News>> =
MutableLiveData()
val news: LiveData<List<News>> = _news
private val _progressVisible: MutableLiveData<Boolean> =
MutableLiveData()
val progressVisible: LiveData<Boolean> =
_progressVisible
fun onCreate() {
viewModelScope.launch {
val user = userRepo.getUser()
_userName.value = user.name
}
viewModelScope.launch {
_progressVisible.value = true
val news = newsRepo.getNews()
.sortedByDescending { it.date }
_news.value = news
_progressVisible.value = false
}
}
}

Instead of viewModelScope, there might be our own scope, and instead of ViewModel, it might be Presenter, Activity, or some other class. It does not matter for our example. As in every class that starts coroutines, we should use StandardTestDispatcher as a part of the scope. Previously, we needed to ...