Unit testing ViewModel in Kotlin Multiplatform project

Yulia
2 min readMay 27, 2021

--

Even though the main reason for using MVVM pattern is in getting the logic part separate from UI and testable, for the modern android project it could be really tricky to write proper unit tests.

In this article let’s try to set up the environment and make our first unit test for a very simple ViewModel in a super cool modern tech stack: KMM + MVVM + Coroutines + Reactive.

Consider we have the following ViewModel:

UseCase contract for better understanding:

Let’s add some basic dependencies for unit testing (of course, you’re encouraged to update versions if needed):

We can now make the first steps in unit test creating:

For now, we have two //TODO issues to be resolved. First, let’s add dependencies for making coroutines work in our tests:

Now let’s add a rule, that allows us to work with coroutines. If you want to understand properly what is going behind the scenes, take a look at this excellent article. And please note, that here for simplicity we are not using CoroutineDispatcher injecting via the constructor, even though it’s a better approach in terms of OOP.

Newly created rule:

The only left problem is to understand how to mock reactive Publisher. You must be surprised, but actually, there is a library for that one too:

The tricky thing here is to make test Publisher response cold, so that it emits items we need not immediately after creation. Considering that in mind, we result in the following code:

That is it! Let’s add all other corner cases and our first unit test will be written and actually working:

All the dependencies in one gist:

If you have any further questions or just want to stay in touch: https://twitter.com/YCoenova

--

--

Yulia
Yulia

Written by Yulia

Death researcher, android dev

No responses yet