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.toml
file 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-mockk
dependency to thetest
bundle. Our updatedtest
bundle 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
mockk
allows us to mock our dependencies. - We are now ready to create our test class. Create a new Kotlin file called
CatsViewModelTest.kt
inside the test directory and add the following code:class PetsViewModelTest...