【发布时间】:2022-09-27 18:33:33
【问题描述】:
我有可以通过这样的代码提供的视图模型:
val retrofitService = RetrofitService.getInstance(requireContext())
val mainRepository = MainRepository(retrofitService)
val viewVM = ViewModelProvider(this, AppVMFactory(mainRepository)).get(AppViewModel::class.java)
我想测试我的视图模型请求等等。由于我的测试需要上下文,我决定使用仪器测试,我可以通过这样的行获取上下文:
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
我遇到的问题与在测试中获取生命周期所有者有关。 ViewModelProvider 有这样的构造函数:
constructor(
private val store: ViewModelStore,
private val factory: Factory,
private val defaultCreationExtras: CreationExtras = CreationExtras.Empty,
)
和:
constructor(owner: ViewModelStoreOwner, factory: Factory) : this(
owner.viewModelStore,
factory,
defaultCreationExtras(owner)
)
它们非常相似。但是我如何在我的测试中创建视图模型?有可能还是只能通过完全不同的方式完成?
标签: android android-testing android-viewmodel instrumented-test