英文:
How is it possible to instantiate a ViewModel in a unit test?
问题
以下codelab在单元测试中实例化了一个ViewModel
,而不使用Robolectric或任何模拟库。
链接:https://developer.android.com/codelabs/basic-android-kotlin-compose-test-viewmodel
这是如何实现的?我原以为ViewModel
是Android库的一部分,不能在JVM中运行。
英文:
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.
答案1
得分: 3
> 这是怎么可能的?
ViewModel
是一个像其他任何 Java 类一样的类。因此,它的实例可以像其他类的实例一样被实例化。
> 我原以为 ViewModel
是 Android 库的一部分,不会在 JVM 中运行。
ViewModel
实际上并不是“Android 库的一部分” - 它是 JetPack
生命周期组件库 的一部分。这些是 Android 核心框架的扩展,但不是其一部分。您可以从ViewModel 的源代码中看到,基本的 ViewModel
类不依赖于核心 Android 框架类,只依赖于其他 JetPack
类和标准的 Java
类。
因此,使用 ViewModel
不需要 Android 运行时环境,这意味着您可以在本地单元测试的 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论