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!
No Comment! Be the first one.