我正在将Dagger-hilt与hilt jetpack集成使用
我的生产依存关系
gpflow.models.GPR((X, logY), kernel)
我的测试依赖项
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'
扩展名为jetpack的表格
by viewModels()
在ViewModel中,我使用的是Jetpack中的private val viewModel: SplashViewModel by viewModels()
@ViewModelInject
它在生产代码中运行良好,但是当使用Robolectric从测试中启动活动时,应用程序将因该异常而崩溃
class SplashViewModel @ViewModelInject constructor(
private val authenticationRepository: AuthenticationRepository
)
这是我的考试班
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
答案 0 :(得分:0)
问题在于,从测试用例启动活动时,它是一个“正常”活动,而不是用@AndroidEntryPoint
注释的Hilt活动。
为了解决此问题,您必须(1)创建要启动的@AndroidEntryPoint
活动,(2)为此创建调试方案。
以下是您所需的所有内容的简单教程:https://www.youtube.com/watch?v=k4zG93ogWFY&t和 https://www.youtube.com/watch?v=B-dJTFeOAqw&t
答案 1 :(得分:0)
使用 public 声明SplashViewModel类,例如
public class SplashViewModel extends ViewModel {
// TODO: Implement the ViewModel
}