单元测试AndroidViewModel类

Alf*_*ano 2 android unit-testing

我正在为我的应用程序编写单元测试,并且在写入时我发现了"减速带".在测试AndroidViewModel的子类时,我缺少用于初始化的Application参数.我已经读过这个使用Robolectric的问题了.

这是我到目前为止已经尝试过的:

  • 使用Robolectric作为问题描述.据我所知,Robolectric可以使用您的自定义Application类进行测试,我不使用自定义应用程序类,因为我不需要它.(应用程序并不复杂).
  • 使用mockito.Mockito抛出一个异常,说不能模拟Context类.
  • 使用InstrumentationRegistry.我将测试类从测试文件夹移动到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
}
Run Code Online (Sandbox Code Playgroud)

Bru*_*lho 5

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

您可以在单元测试中使用Robolectric,在测试目录中,并选择平台Application类.

@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()
    }

}
Run Code Online (Sandbox Code Playgroud)

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

@RunWith(AndroidJUnit4::class)
class ViewModelTest {

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

}
Run Code Online (Sandbox Code Playgroud)

希望它有所帮助!