Dagger not generating components for /test class

后端 未结 8 845
醉梦人生
醉梦人生 2020-12-04 20:57

I am following the guide here: https://github.com/ecgreb/dagger-2-testing-demo

I have the following setup in my app/src/main (the injection and @Provides code omitte

8条回答
  •  春和景丽
    2020-12-04 21:32

    Just to add a bit to the above answer, since there have been some recent changes.

    From Android Gradle plugin version 2.2 and above you will no longer use testApt.

    So from now on you need to put only this in the build.gradle:

    testAnnotationProcessor 'com.google.dagger:dagger-compiler:'
    

    But more than that, what I came here for, is the following: if you need gradle to generate the DaggerComponent classes for you you will have to do a bit extra work.

    Open our build.gradle file and AFTER the android section write this:

    android.applicationVariants.all { variant ->
        if (variant.buildType.name == "debug") {
            def aptOutputDir = new File(buildDir, "generated/source/apt/${variant.unitTestVariant.dirName}")
            variant.unitTestVariant.addJavaSourceFoldersToModel(aptOutputDir)
            assembleDebug.finalizedBy('assembleDebugUnitTest')
        }
    }
    

    This will create the directory build/generated/source/apt/test/ as a Java classes recipient and the last part will trigger the "assembleDebugUnitTest" task that will finally create those Dagger2 components in the folder that was just created.

    Note that this script is just being triggered for the "debug" variant and takes advantage of that build variant using the "assembleDebug" task. If for some reason you need it in other variants just tweak that a bit.

    Why Dagger2 does not do this automatically is beyond me, but hey, I am no pro.

提交回复
热议问题