注入UnitTest类

时间:2017-01-19 17:12:26

标签: java android-studio junit dagger-2

您好我的(部分)项目中使用Dagger 2是完全纯Java而没有Android依赖项的问题。

当我在Gradle视图或控制台(businessModule:test)上使用一些模拟运行单元测试(例如,注入模拟网络连接器返回静态字符串)时,没有问题,所有测试都成功。但是当我在Android Studio中打开文件时,Studio说我的DaggerMockComponent的返回与目标类型不兼容。打开生成的Component-Implementation,我看到Android Studio认为TestUnit-Class(和接口MockComponent)不可用,所以它不知道inject方法返回什么。

我有以下gradle文件:

申请插件:' java'

// allow inject of core into core. https://github.com/griffio/dagger2-example
sourceSets {
    dagger {
        java {
            srcDirs = ['src/dagger/java']
        }
    }
    daggerTest {
        java {
            srcDirs = ['src/daggerTest/java']
        }
    }
}

configurations {
    compileDagger
}

compileJava {
    description = "dagger annotation processor is loaded automatically from classpath"
    sourceSets.dagger.java.srcDirs*.mkdirs()
    classpath += configurations.compileDagger
    options.compilerArgs += [
            '-s', sourceSets.dagger.java.srcDirs.iterator().next()
    ]
}

compileTestJava {
    //dependsOn compileDaggerTestJava
    description = "dagger annotation processor is loaded automatically from classpath"
    sourceSets.daggerTest.java.srcDirs*.mkdirs()
    classpath += configurations.compileDagger
    options.compilerArgs += [
            '-s', sourceSets.daggerTest.java.srcDirs.iterator().next()
            //'-s src/testDaggerJava'
    ]
}

task deleteDagger(type: Delete) {
    delete 'src/dagger', 'src/daggerTest'
}

clean.dependsOn deleteDagger

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    // Force Java 7 as newer versions can not be processed by dex for API 21
    targetCompatibility = '1.7'
    sourceCompatibility = '1.7'

    [...]

    // Dagger for dependency injection
    compile 'com.google.dagger:dagger:2.8'
    testCompile 'com.google.dagger:dagger:2.8'
    compileOnly 'com.google.dagger:dagger-compiler:2.8'
    testCompileOnly 'com.google.dagger:dagger-compiler:2.8'

    [...]

    testCompile 'junit:junit:4.12'

}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

好的大家,经过一个额外的夜晚和对android-apt插件的一些研究后,我偶然发现了纯Java apt(net.ltgt.apt),现在我有了一个与idea-plugin结合的工作解决方案

apply plugin: 'java'
apply plugin: "net.ltgt.apt"
apply plugin: "idea"

task cleanGenerated(type: Delete) {
    delete 'build'
}

clean.dependsOn cleanGenerated


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    // Force Java 7 as newer versions can not be processed by dex for API 21
    targetCompatibility = '1.7'
    sourceCompatibility = '1.7'

    [...]

    // Dagger for dependency injection
    compile 'com.google.dagger:dagger:2.8'
    apt 'com.google.dagger:dagger-compiler:2.8'
    testCompile 'com.google.dagger:dagger:2.8'
    testApt 'com.google.dagger:dagger-compiler:2.8'

    [...]

    testCompile 'junit:junit:4.12'

}

当然你必须在根gradle文件中添加依赖项和插件名,但是在documentation for net.ltgt.apt中写下了 - 希望这也适合你。