👄0. 简言
🤓:现在的安卓是 MVVM 大流行,嗯,不是传染病啊!测试 ViewModel 势在必行。可是,如果你用的是 Ktx,你就测不了。例如:
val vm: ShoppingViewModel by viewModels()
无论你把 vm 换成啥样,如 var,就是不让你测。除非,用旧的方法:
lateinit var viewModel: ShoppingViewModel
onCreate() {
viewModel = ViewModelProvider(...)
}
可是,你就不爽了吧,多了一行,还要打开 private,才能看。
😁:其实,你打包就能测。
💆:我要外卖。
🔌1. Gradle
老套路,外卖需要 Kotlin.Reflect。
😳:怎么成了外卖了?
🤔:… 把这个加进你的 dependencies 。
// Kotlin Reflect
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
🔑2. 加 ProvideModel 方程
- ProvideViewModel.kt
inline fun <reified VM : ViewModel> Fragment.provideViewModel(
noinline ownerProducer: () -> ViewModelStoreOwner = {
this },
noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
): Lazy<VM> =
OverridableLazy(viewModels(ownerProducer, factoryProducer))
// wrapper
class OverridableLazy<T>(var implementation: Lazy<T>): Lazy<T>

本文介绍了如何在使用Ktx的MVVM架构下进行ViewModel的Hilt-Fragment测试。通过添加ProvideModel方程、创建Fragment Factory以及利用LiveData测试方程,详细阐述了测试ViewModel的步骤,包括在测试中如何替换真实的ViewModel以进行模拟测试。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



