Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible to instantiate a ViewModel in a unit test?

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.

like image 490
Tatsuya Fujisaki Avatar asked Sep 11 '25 03:09

Tatsuya Fujisaki


1 Answers

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.

like image 189
dominicoder Avatar answered Sep 13 '25 16:09

dominicoder