【问题标题】:How to get lifecycle owner in instrumented test android?如何在仪器测试android中获得生命周期所有者?
【发布时间】: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


    【解决方案1】:

    这是我对这个问题的解决方案:

    private val appContext: Context = InstrumentationRegistry.getInstrumentation().targetContext
    
        @Test
        fun simpleLogIn() {
            val scenario = launchActivity<HomeScreen>()
            scenario.onActivity { activity ->
                val retrofitService = RetrofitService.getInstance(appContext)
                val mainRepository = MainRepository(retrofitService)
                val viewVM =
                    ViewModelProvider(
                        activity,
                        AppVMFactory(mainRepository)
                    )[AppViewModel::class.java]
            }
    
        }
    

    在这里你可以看到我使用launchActivity 场景。要启用它,您应该在 build.gradle 这样的依赖项中使用:

    androidTestImplementation 'androidx.test:core-ktx:X.X.X'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-02
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多