作者:Viola大人 | 来源:互联网 | 2022-12-09 18:45
我正在为我的应用程序编写单元测试,并且在写入时我发现了"减速带".在测试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
}
Bruno Coelho..
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()
}
}
或者您可以在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()
}
}
希望它有所帮助!
1> Bruno Coelho..:
我遇到了同样的问题,并找到了两个解决方案.
您可以在单元测试中使用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()
}
}
或者您可以在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()
}
}
希望它有所帮助!