Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a ViewModel instance in a test.
Android Kotlin
val viewModel = [1]() Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using ViewModelProvider in unit tests without Android framework.
Trying to instantiate LiveData instead of ViewModel.
✗ Incorrect
You create an instance of your ViewModel class directly in tests to test its logic.
2fill in blank
mediumComplete the code to observe LiveData value changes in a test.
Android Kotlin
viewModel.data.observeForever [1] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using Observer class syntax instead of lambda.
Passing 'this' which is not a valid observer.
✗ Incorrect
In tests, observeForever takes a lambda to react to LiveData changes.
3fill in blank
hardFix the error in the test code to get LiveData value synchronously.
Android Kotlin
val value = viewModel.data.[1]() Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using getValue which returns null if no value is set.
Using observe which requires a lifecycle owner.
✗ Incorrect
getOrAwaitValue is a helper function to get LiveData value in tests synchronously.
4fill in blank
hardFill both blanks to mock a repository and inject it into ViewModel for testing.
Android Kotlin
val mockRepo = [1]() val viewModel = MyViewModel([2])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the class name instead of the mock instance.
Not using a mocking library to create the mock.
✗ Incorrect
Use mockk() to create a mock repository, then pass it to ViewModel constructor.
5fill in blank
hardFill all three blanks to verify a repository method call in ViewModel test.
Android Kotlin
verify(exactly = [1]) { mockRepo.[2]([3]) }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 for exactly means no calls expected.
Not using any() causes verification to fail if argument differs.
✗ Incorrect
Verify that fetchData was called exactly once with any argument.