Recall & Review
beginner
What is the main purpose of testing a ViewModel in Android?
To verify that the ViewModel correctly manages UI-related data and business logic without depending on the Android framework.
Click to reveal answer
beginner
Which testing framework is commonly used for unit testing ViewModels in Kotlin?
JUnit is commonly used for unit testing ViewModels in Kotlin, often combined with libraries like Mockito for mocking dependencies.
Click to reveal answer
intermediate
Why should LiveData be observed using a TestObserver or similar in ViewModel tests?
Because LiveData is lifecycle-aware, it needs a way to emit values in tests without a real lifecycle owner; TestObserver helps capture emitted values for assertions.
Click to reveal answer
intermediate
What is the role of the InstantTaskExecutorRule in ViewModel testing?
It makes LiveData execute each task synchronously during tests, so you can immediately observe changes without waiting for background threads.
Click to reveal answer
intermediate
How do you test a ViewModel function that updates LiveData based on a repository call?
Mock the repository to return expected data, call the ViewModel function, then observe the LiveData and assert it has the expected updated value.
Click to reveal answer
Which rule helps LiveData run synchronously in ViewModel tests?
✗ Incorrect
InstantTaskExecutorRule forces LiveData to execute tasks synchronously, making it easier to test.
What should you mock when testing a ViewModel that depends on a repository?
✗ Incorrect
Mocking the repository isolates the ViewModel logic and controls the data returned for testing.
Why is it important to avoid Android framework dependencies in ViewModel tests?
✗ Incorrect
Avoiding Android framework dependencies makes unit tests faster and easier to run without device or emulator.
Which of these is NOT a good practice when testing LiveData in ViewModels?
✗ Incorrect
Using a real lifecycle owner in unit tests is difficult; TestObserver or similar tools are preferred.
What does a typical ViewModel test verify?
✗ Incorrect
ViewModel tests focus on logic and data updates, especially LiveData changes.
Explain how you would test a ViewModel method that fetches data asynchronously and updates LiveData.
Think about isolating dependencies and capturing LiveData changes.
You got /4 concepts.
Describe the purpose and use of InstantTaskExecutorRule in ViewModel testing.
Consider how LiveData normally works with lifecycle and threads.
You got /3 concepts.