The following codelab instantiates a ViewModel
in a unit test without using Robolectric or any mock library.
https://developer.android.com/codelabs/basic-android-kotlin-compose-test-viewmodel
How is this possible? I thought that ViewModel
, which is part of an Android library, would not run in the JVM.
How is this possible?
ViewModel is a Java class like any other. As such an instance of it can be instantiated like any other.
I thought that ViewModel, which is part of an Android library, would not run in the JVM.
ViewModel
is actually not "part of an Android library" - it is part of the JetPack
lifecycle component library. These are extensions to - but not part of - the core Android framework. You can see from the ViewModel source code that the base ViewModel
class has no dependencies on core Android framework classes - just other JetPack
classes and standard Java
classes.
As such, you don't require the Android runtime to be present to use a ViewModel
which means you can run it on the local unit test JVM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With