Writing tests for your ViewModels
Unlike Model-View-Controller (MVC) and Model-View-Presenter (MVP), MVVM is the favored design pattern in Modern Android Development because of its unidirectional data and dependency flow. Furthermore, it becomes more accessible to unit test, as you will see in this recipe.
Getting ready
We will use our previous recipe, Implementing ViewModel and understanding the state in Compose, to test our logic and state changes.
How to do it…
In this recipe, we will write unit tests to verify our authentication state changes since that is what we have implemented so far:
- Start by creating a
LoginViewModelTest
class in thetest
package:
Figure 3.14 – Created unit test
- We will use the
cashapp/turbine
testing library for coroutine flows to test the flow we have created. Hence, you will need to include the processing code snippet inbuild.gradle
:repositories {
mavenCentral()
}
dependencies...