1

我正在使用带有刀柄喷气背包集成的匕首刀柄

我的生产依赖项

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'

现在在我的活动中,我正在使用by viewModels()扩展表单喷气背包

private val viewModel: SplashViewModel by viewModels()

在我的 ViewModel 中,我使用@ViewModelInject的是 jetpack

class SplashViewModel @ViewModelInject constructor(
    private val authenticationRepository: AuthenticationRepository
)

它在生产代码中运行良好,但是当使用 Robolectric 从测试中启动活动时,应用程序将因此异常而崩溃

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

2 回答 2

0

使用public来声明 SplashViewModel 类,如

public class SplashViewModel extends ViewModel {
    // TODO: Implement the ViewModel
}
于 2020-12-11T06:53:48.840 回答
0

问题是,当从测试用例启动 Activity 时,它是一个“正常”的 Activity,而不是一个带有注释的 Hilt Activity @AndroidEntryPoint

为了解决这个问题,您必须(1)创建一个@AndroidEntryPoint您启动的活动,(2)为此创建调试场景。

这是您需要的所有内容的简单教程:https ://www.youtube.com/watch?v=k4zG93ogWFY&t和 https://www.youtube.com/watch?v=B-dJTFeOAqw&t

于 2020-09-05T19:38:39.490 回答