Last time I tried to use Android Architecture components. I couldn’t make LiveData to run in unit tests. But it turns out it is possible.
When trying to use LiveData in unit test I encountered this crash:
The reason it happens is that thread in unit test is not in Android environment. We can fix it. First add architecture components core-testing artefact like this:
Then add testing rule to test, that installs proper TaskExecutor to AppToolkitTaskExecutor, which drives LiveData execution. This will also make everything run on single a thread. In Kotlin it will look like this:
And that’s it. Now we can test. For example:
Here I create mock Observer
I would say it was quite easy, and the test looks nice and concise.
The source code can be found here