我对Dagger 2依赖项注入有疑问。我在Android项目中使用它,但在Java库模块和单元测试中使用它。
ApiTestModule.kt
@Module
class ApiTestModule {
@Provides
@Named("testDatasource")
fun provideGithubTestDatasource(): GithubDatasourceImpl {
return GithubDatasourceImpl(Mockito.mock(GithubService::class.java))
}
}
TestComponent.kt
@Singleton
@Component(modules = [ApiTestModule::class])
interface TestComponent {
fun inject(test: GithubDatasourceImplTest)
}
GithubDatasourceImplTest.kt
class GithubDatasourceImplTest {
@set:[Inject Named("testDatasource")]
lateinit var datasource: GithubDatasourceImpl
@Before
fun setUp() {
val component = DaggerTestComponent.builder()
.apiTestModule(ApiTestModule())
.build()
component.inject(this)
}
@Test
fun test_create() {
checkNotNull(datasource)
}
}
模块build.gradle
apply plugin: 'java-library'
apply plugin: 'kotlin'
apply plugin: 'kotlin-kapt'
kapt {
generateStubs = true
}
dependencies {
rootProject.ext.apiGithubDependencies.each {
add(it.configuration, it.dependency)
}
}
sourceCompatibility = "1.7"
targetCompatibility = "1.7"
我的错误
错误:
[Dagger/MissingBinding] hr.thekarlo95.api.github.GithubDatasourceImpl cannot be provided without an @Inject constructor or an @Provides-annotated method.
public abstract void inject(@org.jetbrains.annotations.NotNull()
^
hr.thekarlo95.api.github.GithubDatasourceImpl is injected at
hr.thekarlo95.api.github.GithubDatasourceImplTest.setDatasource(p0)
hr.thekarlo95.api.github.GithubDatasourceImplTest is injected at
hr.thekarlo95.api.github.di.TestComponent.inject(hr.thekarlo95.api.github.GithubDatasourceImplTest)
我无法使它正常工作,并且错误消息并没有真正帮助。如果我从fun inject(test: GithubDatasourceImplTest)
中删除了TestComponent
,则所有内容都会编译,但无法将依赖项注入到单元测试中。