android – annotationProcessor + androidTest + dagger2-ThrowExceptions

Exception or error:

For instrumented tests, I have a TestApplication that creates a TestComponent, but the file is not generated anymore (Error:/xxx/TestApplication.java:16: The import.xxx.DaggerTestApplicationComponent cannot be resolved). I’m not able to identify the root cause. I’ve tried different Android Studio (2.2, 2.1.2), different gradle plugin (2.2.0-alpha6, 5, 4) and different versions of dagger (2.2 to 2.6).

Should I use androidTestAnnotationProcessor? (that was not the case before)

edit: to use dagger 2.6, need to add classpath 'com.google.guava:guava:19.0'

update: there was a problem with a Module, hence the Component couldn’t be create. However, using jack (even with debug options), I couldn’t see the problem. For now, reverting to java 7, gradle plugin 2.1.2. That way, no need to specify which guava version, and all the latest libs can be used (dagger 2.6, butterknife 8.2.1, apt 1.8)

How to solve:

I had the same problem with Dagger 2.9. compileDebugAndroidTestSources was completing successfully but the Dagger*Component was not generated.

After struggling for about an hour I landed on this question and finally with some experiments found a solution:

Add

androidTestAnnotationProcessor 'com.google.dagger:dagger-compiler:2.9'

and execute compileDebugAndroidTestSources again. Now sources should be generated (you may have to temporary comment out references to your Dagger*Component in order compilation to succeed) if your graph is OK.

If there is a problem with your graph (e.g. missing @Provides) now you will get an error (in contrast of the previous state without androidTestAnnotationProcessor where the task was completing without an error but sources were not generated)

<rant>

I used to love Dagger but every now and then there are some strange problems with it that make it a big risk for long commercial projects. Also they still don’t have decent documentation for it which makes learning it by new developers very hard. Probably it is not just Dagger’s fault, probably gradle and Android Studio have their part in the problems but I am seriously considering to dump it.

</rant>

###

In addition to the @Ognyan’s answer, Keep in mind that DaggerTestApplicationComponent does not get generated until you build the test.

To build the test, open ActivityTest.kt, right-click on public class ActivityTest and choose Run -> ActivityTest.kt

enter image description here

Leave a Reply

Your email address will not be published. Required fields are marked *