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'll cover the following...
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> = _userNameprivate val _news: MutableLiveData<List<News>> =MutableLiveData()val news: LiveData<List<News>> = _newsprivate val _progressVisible: MutableLiveData<Boolean> =MutableLiveData()val progressVisible: LiveData<Boolean> =_progressVisiblefun onCreate() {viewModelScope.launch {val user = userRepo.getUser()_userName.value = user.name}viewModelScope.launch {_progressVisible.value = trueval 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 ...