Programing

/ test 클래스에 대한 구성 요소를 생성하지 않는 Dagger

lottogame 2020. 12. 10. 08:26
반응형

/ test 클래스에 대한 구성 요소를 생성하지 않는 Dagger


여기 가이드를 따르고 있습니다 : https://github.com/ecgreb/dagger-2-testing-demo

내 앱 / src / main에 다음 설정이 있습니다 (인젝션 및 @Provides 코드 생략).

public class FlingyApplication extends Application {
    @Singleton
    @Component(modules = { FlingyModule.class })
    public interface FlingyComponent
}

@Module
public class FlingyModule

app / src / test에서 :

public class TestFlingyApplication extends Application {
    @Singleton
    @Component(modules = { TestFlingyModule.class })
    public interface TestFlingyComponent extends FlingyComponent
}

@Module
public class TestFlingyModule

지금까지 github 예제와 거의 동일합니다. dagger가 src / main의 컴포넌트 빌더에 대한 코드를 생성 할 때 올바르게 생성됩니다. 그러나 Dagger는 src / test의 컴포넌트 빌더에 대한 코드를 생성하지 않습니다.

내 기본 build.gradle :

dependencies {
    classpath 'com.android.tools.build:gradle:2.1.0-alpha3'

    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.5.1'
}

내 app / build.gradle

apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'


android {
    # There is obviously more in here, but this is the custom part:
    packagingOptions {
        exclude 'META-INF/services/javax.annotation.processing.Processor'
    }
}

dependencies {
    compile 'com.squareup:otto:1.3.8'
    compile 'com.android.support:cardview-v7:23.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.jakewharton:butterknife:7.0.1'

    compile 'com.google.dagger:dagger:2.0.1'
    apt 'com.google.dagger:dagger-compiler:2.0.1'
    compile 'javax.annotation:javax.annotation-api:1.2'

    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'io.reactivex:rxjava:1.1.0'

    testCompile 'com.neenbedankt.gradle.plugins:android-apt:1.4'
    testCompile 'junit:junit:4.12'
    testCompile 'org.robolectric:robolectric:3.0'
    testCompile 'org.mockito:mockito-core:1.10.19'
}

그래서 빌드 할 때 DaggerFlingyApplication_FlingyComponent수업을 받지만DaggerTestFlingyApplication_TestFlingyComponent

흥미로운 점은 라인을 전환하면 다음과 같습니다.

apt 'com.google.dagger:dagger-compiler:2.0.1'
# TO
compile 'com.google.dagger:dagger-compiler:2.0.1'

실행하면 다음이 표시됩니다 ./gradlew compileDebugUnitTestSources.

:app:compileDebugJavaWithJavac
Note: /app/build/generated/source/apt/debug/com/jy/flingy/DaggerFlingyApplication_FlingyComponent.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
:app:preDebugUnitTestBuild UP-TO-DATE
:app:prepareDebugUnitTestDependencies
:app:compileDebugUnitTestJavaWithJavac
Note: /app/build/intermediates/classes/test/debug/com/jy/flingy/DaggerTestFlingyApplication_TestFlingyComponent.java uses unchecked or unsafe operations.

왜 그것이 중간체로 빌드되는지 모르겠고 apt대신 사용할 build.gradle 파일이 필요하다고 가정 compile하지만이 작업을 수행하는 방법을 알아낼 수 없습니다. 나는 그것이 절대적으로 가능하다는 것을 압니다.


build.gradle계측 테스트 를 위해 파일에 다음을 추가해야합니다 .

androidTestApt 'com.google.dagger:dagger-compiler:<version>'

또는 JUnit 테스트의 경우 :

testApt 'com.google.dagger:dagger-compiler:<version>'

이는 테스트 구성 요소에 대한 Dagger 코드를 생성하는 데 필요합니다.


편집 :

jack도구 체인을 사용하는 경우 Android 테스트를 위해 다음을 추가하십시오.

androidTestAnnotationProcessor 'com.google.dagger:dagger-compiler:<version>'

JUnit 테스트의 경우 :

testAnnotationProcessor 'com.google.dagger:dagger-compiler:<version>'

편집 :

혹시 사용하고있는 kotlin-kapt코 틀린 코드를 사용하여 다음을 위해 :

kaptAndroidTest 'com.google.dagger:dagger-compiler:<version>'

또는 JUnit 테스트의 경우 :

kaptTest 'com.google.dagger:dagger-compiler:<version>'

자세한 내용은 링크를 확인하십시오 .


최근에 몇 가지 변경 사항이 있으므로 위의 답변에 약간을 추가하십시오.

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:<version>'

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.


For Android Studio 3 and dagger 2.13 the already mentioned annotation processors are needed:

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

But also do not forgot to do this for the instrumented test under androidTest:

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

You might get the impression that this alone does not work, because the DaggerXYZ classes are not generated. After hours I found out that the test source generation is only triggered when the tests are executed. If you start a test or androidTest from Android Studio the source generation should be triggered.

If you need this earlier trigger gradle manually:

gradlew <moduledirectory>:compile<Flavor>DebugAndroidTestSources
gradlew <moduledirectory>:compile<Flavor>DebugTestSources

Replace Debug if you run a test in a different build type.

Note:

If you are using multiDexEnable = true you might get an error:

Test running failed: Instrumentation run failed due to 'java.lang.IncompatibleClassChangeError'

Use a different runner in this case:

android {

  defaultConfig {
    multiDexEnabled true
    testInstrumentationRunner "com.android.test.runner.MultiDexTestRunner"

If you added kaptAndroidTest for dagger dependencies and still not getting test components when rebuild your project, try running assembleAndroidTest.


Adding to the above solution and adding the testKapt and androidTestKapt for dagger, I had the problem that my modules and components had the wrong imports as a result of missing imports

e.g

 import android.support.test.espresso.core.deps.dagger.Module
 import android.support.test.espresso.core.deps.dagger.Module

instead of

import dagger.Module
import dagger.Provides

Hope this helps


If you are using kotlin use "kaptAndroidTest" to generate dagger component for android tests in your build.gradle file.


Hi even after adding all gradle dependenices and annotations if it still doesnt work then you need to run assembleAndroidTest gradle script for this. Simply make an empty test case and run it. It will do the job for you. Cheers

참고URL : https://stackoverflow.com/questions/36231457/dagger-not-generating-components-for-test-class

반응형