Dagger 2-如果没有@Inject构造函数或@Provides注释的方法,则无法提供

时间:2018-07-06 20:58:17

标签: java android kotlin dagger-2

我对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,则所有内容都会编译,但无法将依赖项注入到单元测试中。

0 个答案:

没有答案