AndroidViewModel类的单元测试

4
我正在为我的应用程序编写单元测试,并且在编写它们时遇到了一些问题。 在测试AndroidViewModel的子类时,我缺少其初始化的 Application 参数。 我已经阅读了这篇使用Robolectric的文章
这是我迄今为止尝试过的方法:
  • 如问题描述使用Robolectric。据我所知,Robolectric可以用于测试您的自定义Application类,但我没有使用自定义的应用程序类,因为我不需要它(该应用程序并不那么复杂)。
  • 使用mockito。Mockito引发异常,指出无法模拟Context类。
  • 使用InstrumentationRegistry。将测试类从test文件夹移动到androidTest文件夹,以便访问 androidTestImplementation 依赖项,我尝试使用InstrumentationRegistry.getContext()并将其转换为Application,当然这样做不起作用,会抛出一个类型转换异常。 尽管我感到很愚蠢,但还是值得一试。
我只想实例化我的AndroidViewModel类,以便可以调用它们的公共方法,但需要Application参数。 我该怎么做?
fun someTest() {
   val testViewModel = MyViewModelThatExtendsFromAndroidViewModel(**missing application parameter**)
   testViewModel.foo() // The code never reaches here as the testViewModel cant be initializated
}
1个回答

11

我曾遇到过同样的问题,并找到了两个解决方案。

你可以在测试目录中使用Robolectric进行单元测试,选择平台应用程序类。

@RunWith(RobolectricTestRunner::class)
@Config(application = Application::class)
class ViewModelTest {

    @Test
    @Throws(Exception::class)
    fun someTest() {
        val application = RuntimeEnvironment.application
        val testViewModel = MyViewModelThatExtendsFromAndroidViewModel(application)
        testViewModel.foo()
    }

}

或者您可以在androidTest目录中使用InstrumentationTest,并将InstrumentationRegistry.getTargetContext().applicationContext转换为Application

@RunWith(AndroidJUnit4::class)
class ViewModelTest {

    @Test
    @Throws(Exception::class)
    fun someTest() {
        val application = ApplicationProvider.getApplicationContext() as Application
        val testViewModel = MyViewModelThatExtendsFromAndroidViewModel(application)
        testViewModel.foo()
    }

}

希望它有所帮助!


你好,感谢你的回答。我写了一个小的Android项目来测试这段代码,而且它非常完美地运行了。我将选择你的回答作为采纳答案,并且我已经将该项目添加到Github仓库中。https://github.com/AlfredoBejarano/Android-Kotlin-Demos/tree/master/ViewModelTesting再次感谢! - Alfredo Bejarano
更新链接:https://github.com/AlfredoBejarano/Android-Kotlin-Demos/tree/master/ViewModelTestingDemo - xarly
InstrumentationRegistry.getTargetContext()现在已经被弃用,可以使用更易于阅读的ApplicationProvider.getApplicationContext()代替 :-) - IainCunningham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接