Unit Testing Lifecycle and State in ViewModels | by Marcello Galhardo | Android Developers | Mar, 2025

Unit Testing Lifecycle and State in ViewModels | by Marcello Galhardo | Android Developers | Mar, 2025

Home » News » Unit Testing Lifecycle and State in ViewModels | by Marcello Galhardo | Android Developers | Mar, 2025
Table of Contents

You’ll be able to take a look at a ViewModel by merely creating an occasion utilizing its constructor in your take a look at code. Nevertheless, this method has limitations — there isn’t a easy technique to:

With ViewModelScenario, these at the moment are straightforward to check, serving to you catch errors associated to ViewModel clean-up and saved state.

First, add the dependency to your Gradle file. It’s obtainable from 2.9.0-alpha08:

implementation("androidx.lifecycle:lifecycle-viewmodel-testing:{model}")

Subsequent, outline your ViewModel:

class MyViewModel(
scope: CoroutineScope,
val deal with: SavedStateHandle,
) : ViewModel(scope) { … }

/* Class utilized by SavedStateHandle. */
@Parcelize
information class MyData(
val identify: String,
val surname: String,
) : Parcelable

Lastly, write a unit take a look at to your ViewModel utilizing a ViewModelScenario:

class MyViewModelTest {

@Check
enjoyable testStateRestoration() = runTest { // this: TestScope
viewModelScenario { // this: CreationExtras
MyViewModel(
scope = this@runTest,
deal with = createSavedStateHandle(),
)
}.use { it: ViewModelScenario ->
// Set a ViewModel state.
it.viewModel.deal with["key"] = MyData("John", "Doe")

// Recreate ViewModel, simulating a state restoration
// (together with parcelizing).
it.recreate()

// Confirm state is restored accurately after parcelizing.
assertThat(it.viewModel.deal with["key"])
.isEqualTo(MyData("John", "Doe"))
}
}
}

We invite you to check out the brand new API and share any points or suggestions by way of our Lifecycle situation tracker.

Blissful testing!

Supply hyperlink

author avatar
roosho Senior Engineer (Technical Services)
I am Rakib Raihan RooSho, Jack of all IT Trades. You got it right. Good for nothing. I try a lot of things and fail more than that. That's how I learn. Whenever I succeed, I note that in my cookbook. Eventually, that became my blog. 
share this article.

Enjoying my articles?

Sign up to get new content delivered straight to your inbox.

Please enable JavaScript in your browser to complete this form.
Name