Testing our ViewModels
Our ViewModel class fetches data from the repository and exposes it to the UI. To test our ViewModel, we will write unit tests. Let us start by setting up the test dependencies in our version catalog:
- Open the
libs.version.tomlfile and add the following versions in the versions section:mockk = "1.13.3"
- Next, in the libraries section, add the following:
test-mockk = { module = "io.mockk:mockk", version.ref = "mockk" } - Add the
test-mockkdependency to thetestbundle. Our updatedtestbundle should now look like this:test = ["test-mock-webserver", "test-coroutines", "test-truth", "test-mockk"]
- Click on the Sync Now button at the top to add the dependencies. Adding
mockkallows us to mock our dependencies. - We are now ready to create our test class. Create a new Kotlin file called
CatsViewModelTest.ktinside the test directory and add the following code:class PetsViewModelTest...