我目前正在阅读这篇文章,尝试使用 Kotlin 在 android 中模拟 dagger 依赖项,但遇到了一些麻烦。
我收到一条错误消息,提示 activityInjector 未初始化。
我究竟做错了什么?
测试应用组件
@Singleton
@Component(
modules = [
AndroidSupportInjectionModule::class,
TestAppModule::class,
ActivityModule::class,
FragmentModule::class,
ViewModelModule::class
]
)
interface TestAppComponent : AndroidInjector<TestApp> {
@Component.Builder
abstract class Builder : AndroidInjector.Builder<TestApp>() {
abstract fun appModule(appModule: TestAppModule): Builder
}
}
测试应用
class TestApp: Application(), HasActivityInjector {
@Inject
lateinit var activityInjector: DispatchingAndroidInjector<Activity>
override fun activityInjector(): AndroidInjector<Activity> = activityInjector
}
测试喷油器
class TestInjector(private val testAppModule: TestAppModule) {
fun inject() {
val testApp= ApplicationProvider.getApplicationContext() as TestApp
DaggerTestAppComponent
.builder()
.appModule(testAppModule)
.create(testApp)
.inject(testApp)
}
}
活动模块
@Module
abstract class ActivityModule {
@ContributesAndroidInjector
abstract fun provideNavigationActivity(): NavigationActivity
}
仪表化单元测试
@Rule
@JvmField
var navigationActivityTestRule = ActivityTestRule(NavigationActivity::class.java, true, true)
@MockK
private lateinit var repo: Repo
@Before
fun setUp() {
MockKAnnotations.init(this)
TestInjector(TestAppModule(repo)).inject()
}