我正在将Dagger-Hilt与Hilt Jetpack集成使用
我的生产依存关系
implementation "com.google.dagger:dagger:2.28"
kapt "com.google.dagger:dagger-compiler:2.28"
implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha01'
kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha01'
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
我的测试依赖项testImplementation "com.google.dagger:hilt-android-testing:$hilt_version"
kaptTest "com.google.dagger:hilt-android-compiler:$hilt_version"
testImplementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha01'
kaptTest 'androidx.hilt:hilt-compiler:1.0.0-alpha01'
现在在我的 Activity 中,我使用的是jett扩展包中的by viewModels()
扩展名private val viewModel: SplashViewModel by viewModels()
在我的ViewModel中,我正在使用jetpack的@ViewModelInject
class SplashViewModel @ViewModelInject constructor(
private val authenticationRepository: AuthenticationRepository
)
在生产代码中可以正常工作,但是在使用Robolectric从测试中启动 Activity 时,应用程序会因出现此异常而崩溃java.lang.RuntimeException: Cannot create an instance of class com.example.SplashViewModel
这是我的考试课@RunWith(RobolectricTestRunner::class)
@Config(sdk = [Build.VERSION_CODES.O_MR1], application = TestApplication::class)
@HiltAndroidTest
class SplashActivityTest {
private val authenticationRepository: AuthenticationRepository = mockk(relaxed = true)
@get:Rule
val rule = HiltAndroidRule(this)
@get:Rule
var activityRule = IntentsTestRule(SplashActivity::class.java)
}
这是我的TestApplication
类class TestApplication : MultiDexApplication(), GeneratedComponentManager<Any>,
TestApplicationComponentManagerHolder {
private var componentManager: TestApplicationComponentManager? = null
override fun onCreate() {
super.onCreate()
JodaTimeAndroid.init(this)
}
override fun attachBaseContext(base: Context?) {
super.attachBaseContext(base)
componentManager = TestApplicationComponentManager(this)
}
override fun componentManager(): Any? {
return componentManager
}
override fun generatedComponent(): Any {
return componentManager!!.generatedComponent()
}
}
最佳答案
问题是从测试用例启动 Activity 时,它是“正常” Activity ,而不是用@AndroidEntryPoint
注释的Hilt Activity 。
为了解决此问题,您必须(1)创建要启动的@AndroidEntryPoint
Activity ,(2)为此创建调试方案。
这是您需要的所有内容的简单教程:https://www.youtube.com/watch?v=k4zG93ogWFY&t和
https://www.youtube.com/watch?v=B-dJTFeOAqw&t
关于android - java.lang.RuntimeException:无法在单元测试中创建ViewModel类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62818294/