Lifecycle 2.9.0-alpha01 introduced ViewModelScenario, a helper that simplifies unit testing for ViewModels.

Why It Matters

You can test a ViewModel by simply creating an instance using its constructor in your test code. However, this approach has limitations — there is no straightforward way to:

With ViewModelScenario, these are now easy to test, helping you catch errors related to ViewModel clean-up and saved state.

How to Use

First, add the dependency to your Gradle file:

implementation("androidx.lifecycle:lifecycle-viewmodel-testing:2.9.0-alpha10")

Next, define your ViewModel:

class MyViewModel(
  scope: CoroutineScope,
  val handle: SavedStateHandle,
) : ViewModel(scope) {
  // collapsed for simplicity
}

Now, write a unit test for your ViewModel using a ViewModelScenario:

class MyViewModelTest {

  @Test
  fun testStateRestoration() = runTest { // this: TestScope
    viewModelScenario { // this: CreationExtras
        MyViewModel(
          scope = this@runTest,
          handle = createSavedStateHandle(),
        )
    }.use { scenario: ViewModelScenario ->
      // Set a `ViewModel` state.
      scenario.recreate()
      // Assert state is restored correctly.
    }
  }
}

Test in Details

ℹ️ If you enjoyed the article you might enjoy following me on Bluesky. ℹ️