I have an Android project in process of migration from Java to Kotlin. In this project, I have a pure Kotlin module where I'm implementing a API Client with the following build.gradle:
apply plugin: 'kotlin'
apply plugin: 'kotlin-kapt'
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlin_version}"
implementation "com.squareup.retrofit2:retrofit:${retrofit_version}"
implementation "com.squareup.retrofit2:converter-gson:${retrofit_version}"
implementation "com.google.code.gson:gson:${gson_version}"
implementation "com.squareup.okhttp3:logging-interceptor:${okhttp_version}"
implementation "io.reactivex.rxjava2:rxjava:${rx_java_version}"
implementation "io.reactivex.rxjava2:rxkotlin:${rx_kotlin_version}"
implementation "com.jakewharton.retrofit:retrofit2-rxjava2-adapter:${retrofit2_rxjava2_adapter_version}"
compileOnly "javax.annotation:jsr250-api:${jsr250_version}"
implementation "com.google.dagger:dagger:${dagger_version}"
kapt "com.google.dagger:dagger-compiler:${dagger_version}"
testImplementation "junit:junit:${junit_version}"
testImplementation "org.mockito:mockito-core:${mockito_version}"
testImplementation "org.hamcrest:hamcrest-junit:${hamcrest_version}"
testImplementation "com.squareup.okhttp3:mockwebserver:${mockwebserver_version}"
// Dependence injection
kaptTest "com.google.dagger:dagger-compiler:${dagger_version}"
}
There is an Annotation Processor dependency for unit tests:
kaptTest "com.google.dagger:dagger-compiler:${dagger_version}"
I can see the generated sources on build/generated/source/kapt/test directory, but they are not visible to the test sources, that is, is not possible to import the generated DaggerUnitTestComponent to inject dependencies, for exemple. And I'm having trouble to get it done.
This kind of thing I had already done with success on a Android project, with the help of this StackOverflow answer and the following snippet added to build.gradle, but for a pure Kotlin/Java project, it is not applicable.
android.applicationVariants.all {
def aptOutputDir = new File(buildDir, "generated/source/apt/${it.unitTestVariant.dirName}")
it.unitTestVariant.addJavaSourceFoldersToModel(aptOutputDir)
}
Is valid to say that I'm using Android Studio 3.0.1 and Kotlin 1.2.10. The sources of Kotlin library module lies on src/main/java and src/test/java.
You might want to take a look at an example of a Kotlin project that uses dagger: (here)
From what I see, the test sources that use the generated classes should compile just fine during a Gradle build, but the IDE might not pick them up correctly.
Try updating Kotlin to a newer version in the project (1.2.10
should handle this). If that does not help, try using the idea
plugin as in the example above, configured for the test generated sources as follows:
apply plugin: 'idea'
idea {
module {
testSourceDirs += file('build/generated/source/kapt/test')
generatedSourceDirs += file('build/generated/source/kapt/test')
}
}