0
0
Android Kotlinmobile~10 mins

ViewModel testing in Android Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
ALiveData
BMyViewModel
CViewModelProvider
DMutableLiveData
Attempts:
3 left
💡 Hint
Common Mistakes
Using ViewModelProvider in unit tests without Android framework.
Trying to instantiate LiveData instead of ViewModel.
2fill in blank
medium

Complete 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'
A{ value -> println(value) }
B(value) -> println(value)
CObserver { value -> println(value) }
Dthis
Attempts:
3 left
💡 Hint
Common Mistakes
Using Observer class syntax instead of lambda.
Passing 'this' which is not a valid observer.
3fill in blank
hard

Fix 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'
ApostValue
BgetValue
Cobserve
DgetOrAwaitValue
Attempts:
3 left
💡 Hint
Common Mistakes
Using getValue which returns null if no value is set.
Using observe which requires a lifecycle owner.
4fill in blank
hard

Fill 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'
Amockk
BmockRepo
Crepository
Dmock
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the class name instead of the mock instance.
Not using a mocking library to create the mock.
5fill in blank
hard

Fill 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'
A1
BfetchData
Cany()
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 for exactly means no calls expected.
Not using any() causes verification to fail if argument differs.