How to make generated Java test sources recognizable by IDE
The background
Starting from Android Gradle plugin 2.2 built-in configuration for annotation processors is available. Previously that functionality has been provided by 3rd party project android-apt
What is that configuration and why it is useful? All that is explained in another blog post: Android Gradle configurations.
The problem
There is a little issue with new configuration. Namely files placed in test source sets are not added to Java model thus they are not recognized by IDE (Android Studio) and marked red however they are normally compilable.
When generated test sources would be needed? Examples includes Dagger (test-only components) and Robolectric shadows (resetters).
I’ve raised an issue on Android Issue Tracker but unfortunately it is not yet fixed at the time of writing (over 4 months after raising).
The solution
Workaround is pretty much easy. We just need to call addJavaSourceFoldersToModel
on relevant (usually all) build variants with appropriate argument. Here is a complete snippet for build.gradle
:
1 2 3 4 | android.applicationVariants.all { def aptOutputDir = new File(buildDir, "generated/source/apt/${it.unitTestVariant.dirName}") it.unitTestVariant.addJavaSourceFoldersToModel(aptOutputDir) } |
For library projects replace applicationVariants
with libraryVariants
. Voilà!
About the author
Ready to take your business to the next level with a digital product?
We'll be with you every step of the way, from idea to launch and beyond!