0
0
Android Kotlinmobile~7 mins

ViewModel testing in Android Kotlin

Choose your learning style9 modes available
Introduction

Testing ViewModels helps ensure your app's data logic works correctly without needing the full app UI. It catches bugs early and makes your app more reliable.

When you want to check if your ViewModel updates data correctly after user actions.
When you need to verify that LiveData emits the right values in response to events.
When you want to test business logic separately from UI components.
When you want to automate tests to avoid manual checking of app behavior.
When you want to ensure your ViewModel handles errors and loading states properly.
Syntax
Android Kotlin
class MyViewModelTest {
  private lateinit var viewModel: MyViewModel

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

  @Test
  fun testExample() {
    // test code here
  }
}

Use @Before to set up your ViewModel before each test.

Use @Test to mark functions that run as tests.

Examples
This test checks if calling increment() increases the count LiveData value by 1.
Android Kotlin
class CounterViewModelTest {
  private lateinit var viewModel: CounterViewModel

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

  @Test
  fun increment_increasesCount() {
    viewModel.increment()
    assertEquals(1, viewModel.count.value)
  }
}
This test verifies that a successful login updates the loginSuccess LiveData to true.
Android Kotlin
class LoginViewModelTest {
  private lateinit var viewModel: LoginViewModel

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

  @Test
  fun login_withValidCredentials_setsSuccess() {
    viewModel.login("user", "pass")
    assertEquals(true, viewModel.loginSuccess.value)
  }
}
Sample App

This example shows a simple ViewModel with a count LiveData and an increment function. The test checks that calling increment updates the count from 0 to 1.

Android Kotlin
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class SimpleViewModel : ViewModel() {
  val count = MutableLiveData(0)

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

// Test class
import org.junit.Before
import org.junit.Test
import org.junit.Assert.assertEquals

class SimpleViewModelTest {
  private lateinit var viewModel: SimpleViewModel

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

  @Test
  fun increment_increasesCount() {
    viewModel.increment()
    assertEquals(1, viewModel.count.value)
  }
}
OutputSuccess
Important Notes

Use MutableLiveData to hold data in ViewModel that can change.

Use assertEquals(expected, actual) to check if your test result matches what you expect.

Tests run quickly and do not need the full Android UI to work.

Summary

ViewModel testing checks your app's data logic without UI.

Use @Before to prepare your ViewModel before tests.

Use assertions like assertEquals to verify expected results.