Bird
Raised Fist0
Android Kotlinmobile~20 mins

ViewModel testing in Android Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
ViewModel Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate
2:00remaining
What is the output when LiveData is observed in a ViewModel test?
Given a ViewModel with a LiveData that emits a value, what will the observer receive after the value is set?
Android Kotlin
class MyViewModel : ViewModel() {
  private val _data = MutableLiveData<String>()
  val data: LiveData<String> = _data

  fun updateData(value: String) {
    _data.value = value
  }
}

// In test:
val viewModel = MyViewModel()
var observedValue: String? = null
viewModel.data.observeForever { observedValue = it }
viewModel.updateData("Hello")
AobservedValue will be "Hello"
BobservedValue will be "" (empty string)
CobservedValue will be null
DThe test will throw an exception
Attempts:
2 left
💡 Hint
LiveData notifies observers immediately when value changes.
❓ lifecycle
intermediate
2:00remaining
What happens if you observe LiveData without a LifecycleOwner in a ViewModel test?
In a ViewModel test, what is the effect of calling observeForever on LiveData instead of observe with a LifecycleOwner?
Android Kotlin
val liveData = MutableLiveData<Int>()
liveData.observeForever { println(it) }
liveData.value = 5
AThe observer receives the value 5 immediately
BThe observer never receives any value
CThe code throws a NullPointerException
DThe observer receives the value only when lifecycle is started
Attempts:
2 left
💡 Hint
observeForever does not depend on lifecycle state.
🔧 Debug
advanced
2:30remaining
Why does this ViewModel test fail to observe LiveData updates?
Consider this test code snippet. Why does observedValue remain null after updateData is called?
Android Kotlin
class MyViewModel : ViewModel() {
  private val _data = MutableLiveData<String>()
  val data: LiveData<String> = _data

  fun updateData(value: String) {
    _data.value = value
  }
}

// Test code:
val viewModel = MyViewModel()
var observedValue: String? = null
viewModel.data.observe { observedValue = it }
viewModel.updateData("Test")
AobservedValue is overwritten immediately after assignment
BMutableLiveData value is not set correctly
CupdateData is not called on the main thread
Dobserve requires a LifecycleOwner, which is missing, so observer is not registered
Attempts:
2 left
💡 Hint
observe needs a lifecycle to work properly in tests.
🧠 Conceptual
advanced
2:30remaining
What is the main benefit of using a TestCoroutineDispatcher in ViewModel testing?
Why do we use TestCoroutineDispatcher or similar in ViewModel tests that use coroutines?
AIt automatically fixes all coroutine bugs in the ViewModel
BIt allows controlling coroutine execution and timing for predictable tests
CIt disables coroutine execution to speed up tests
DIt replaces LiveData with a synchronous data source
Attempts:
2 left
💡 Hint
Think about how to make asynchronous code run predictably in tests.
📝 Syntax
expert
3:00remaining
What error does this ViewModel test code produce?
Analyze the following test code snippet. What error will it raise when run?
Android Kotlin
class MyViewModel : ViewModel() {
  private val _count = MutableLiveData<Int>()
  val count: LiveData<Int> = _count

  fun increment() {
    _count.value = (_count.value ?: 0) + 1
  }
}

// Test code:
val viewModel = MyViewModel()
var observedCount: Int? = null
viewModel.count.observeForever { observedCount = it }
viewModel.increment()
viewModel.increment()
AIllegalStateException due to observing LiveData twice
BNullPointerException because _count.value is null initially
CNo error, observedCount will be 2
DCompilation error due to missing import
Attempts:
2 left
💡 Hint
Check how the Elvis operator ?: handles null values.

Practice

(1/5)
1.

What is the main purpose of testing a ViewModel in Android development?

easy
A. To validate user input directly on the screen
B. To verify the data handling and business logic without UI involvement
C. To test the navigation between different screens
D. To check the layout and visual appearance of the app

Solution

  1. Step 1: Understand ViewModel role

    The ViewModel holds and manages UI-related data but does not handle UI rendering.
  2. Step 2: Identify testing focus

    Testing ViewModel focuses on data logic and state management, not UI or navigation.
  3. Final Answer:

    To verify the data handling and business logic without UI involvement -> Option B
  4. Quick Check:

    ViewModel testing = data logic check [OK]
Hint: ViewModel tests focus on data, not UI or navigation [OK]
Common Mistakes:
  • Confusing ViewModel testing with UI testing
  • Thinking ViewModel tests check screen layouts
  • Assuming navigation is tested in ViewModel tests
2.

Which annotation is commonly used to set up a ViewModel instance before each test method runs?

easy
A. @Ignore
B. @Test
C. @After
D. @Before

Solution

  1. Step 1: Recall JUnit lifecycle annotations

    @Before runs before each test method to prepare test environment.
  2. Step 2: Match annotation to ViewModel setup

    Use @Before to initialize ViewModel before tests run.
  3. Final Answer:

    @Before -> Option D
  4. Quick Check:

    Setup before tests = @Before [OK]
Hint: Use @Before to prepare ViewModel before each test [OK]
Common Mistakes:
  • Using @Test instead of @Before for setup
  • Confusing @After with setup annotation
  • Skipping setup annotation entirely
3.

Given the following test code snippet, what will be the value of result after running the test?

class MyViewModelTest {
  private lateinit var viewModel: MyViewModel

  @Before
  fun setup() {
    viewModel = MyViewModel()
  }

  @Test
  fun testIncrement() {
    viewModel.increment()
    val result = viewModel.counter
  }
}

Assuming counter starts at 0 and increment() adds 1.

medium
A. 1
B. 0
C. null
D. Throws an exception

Solution

  1. Step 1: Understand initial state

    ViewModel's counter starts at 0 before increment.
  2. Step 2: Apply increment method

    Calling increment() adds 1, so counter becomes 1.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    Initial 0 + 1 increment = 1 [OK]
Hint: Increment adds 1 to counter starting at 0 [OK]
Common Mistakes:
  • Assuming counter remains 0 after increment
  • Thinking result is null without initialization
  • Expecting an exception without error in code
4.

Identify the error in this ViewModel test code snippet:

class SampleViewModelTest {
  private lateinit var viewModel: SampleViewModel

  @Test
  fun testReset() {
    viewModel.reset()
    assertEquals(0, viewModel.counter)
  }
}

Assuming viewModel is not initialized anywhere else.

medium
A. Missing @Before setup to initialize viewModel before test
B. Incorrect assertEquals parameter order
C. reset() method does not exist in ViewModel
D. Test method missing @Test annotation

Solution

  1. Step 1: Check viewModel initialization

    viewModel is declared but never initialized before test runs.
  2. Step 2: Identify missing setup

    Without @Before method to initialize viewModel, calling reset() causes error.
  3. Final Answer:

    Missing @Before setup to initialize viewModel before test -> Option A
  4. Quick Check:

    Initialize viewModel before test = @Before needed [OK]
Hint: Always initialize ViewModel before tests with @Before [OK]
Common Mistakes:
  • Forgetting to initialize viewModel before use
  • Mixing assertEquals parameter order
  • Assuming reset() method is missing without checking
5.

You want to test a ViewModel method that fetches data asynchronously and updates a LiveData property. Which approach is best to test this behavior?

hard
A. Mock the LiveData property and verify it was called
B. Call the method and immediately check LiveData value without waiting
C. Use a coroutine test rule to run suspend functions and observe LiveData changes synchronously
D. Test only the UI observing the LiveData, not the ViewModel method

Solution

  1. Step 1: Understand asynchronous data fetching

    ViewModel uses coroutines to fetch data and update LiveData asynchronously.
  2. Step 2: Use coroutine test tools

    Coroutine test rules allow running suspend functions in tests synchronously for reliable assertions.
  3. Step 3: Observe LiveData changes properly

    Observing LiveData synchronously ensures test waits for updates before asserting values.
  4. Final Answer:

    Use a coroutine test rule to run suspend functions and observe LiveData changes synchronously -> Option C
  5. Quick Check:

    Async ViewModel test = coroutine test rule + LiveData observe [OK]
Hint: Use coroutine test rule to handle async LiveData updates [OK]
Common Mistakes:
  • Checking LiveData immediately without waiting
  • Mocking LiveData instead of testing real updates
  • Testing UI instead of ViewModel logic
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard