How to make viewModelScope’s extensions testable? (fixing on the previous article)
In the previous article, I have introduced a bunch of extensions to use in viewModels. But with those extensions, viewModels could no longer be tested (Thanks to pentiux comment). As we know the best practice is to Injecting Dispatchers instead of hardcoding when creating new coroutines.
According to what was said, I want to modify the code so that it can be easily tested. The first step is to define
DispatcherProvider interface to hold all default dispatchers and lately can be mocked with TestDispacher. We can have two different implementations of this interface, one for production codes and other one for testing.
ViewModel has to change a bit (please let me know if you have a better way) so we can use the extensions we defined earlier.
The BaseViewModel implemented
DispatcherProvider and delegated it to constructor’s parameter of that type. Now we can inject different implementations of our DispatcherProvider. But before that we need to update extensions too.
That’s was all changes needed to make viewModels testable. There is a simple test that approve my claim.
You can find the complete project at the following Github repository. If you found any mistakes or problems please let me know. Actually I’m learning and always there is a chance to make a mistake!.
GitHub - dariush-fathie/ViewModelExtensions: This Repository contains bunch of viewModelExtensions…
This Repository contains bunch of viewModelExtensions to simplify viewModels - GitHub …
Thanks all who read my article.