用测试类编译jar

时间:2016-02-18 16:25:56

标签: android android-gradle

如何在android中编译带有测试类的jar?我正在使用android gradle插件1.3.1:

classpath 'com.android.tools.build:gradle:1.3.1'

我试过了:

task testSourcesJar(type: Jar) {
    from android.sourceSets.test.java.srcDirs
}

它创建了完全定义的内容:带有测试源的jar,而不是编译类。编译的classess在哪里以及我应该依赖哪个任务来创建带有测试类的jar?

我需要它为另一个项目准备测试工件,它必须扩展一些测试类。

下面是整个build.gradle和我的修改。这是谷歌的排球图书馆。

// NOTE: The only changes that belong in this file are the definitions
// of tool versions (gradle plugin, compile SDK, build tools), so that
// Volley can be built via gradle as a standalone project.
//
// Any other changes to the build config belong in rules.gradle, which
// is used by projects that depend on Volley but define their own
// tools versions across all dependencies to ensure a consistent build.
//
// Most users should just add this line to settings.gradle:
//     include(":volley")
//
// If you have a more complicated Gradle setup you can choose to use
// this instead:
//     include(":volley")
//     project(':volley').buildFileName = 'rules.gradle'

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.1'
    }
}

apply plugin: 'com.android.library'

repositories {
    jcenter()
}

android {
    compileSdkVersion 22
    buildToolsVersion = '22.0.1'
}


task testSourcesJar(type: Jar, dependsOn: 'testClasses') {
    from android.sourceSets.test.java.srcDirs
}

configurations {
    testArtifacts
}

artifacts {
    testArtifacts testSourcesJar
}

apply from: 'rules.gradle'

2 个答案:

答案 0 :(得分:1)

看起来在这里发布一个问题可以提供一些解决问题的灵感......无论如何,有解决方案:

task testClassesJar(type: Jar, dependsOn: 'compileReleaseUnitTestSources') {
    from 'build/intermediates/classes/test/release'
}

configurations {
    tests
}

artifacts {
    tests testClassesJar
}

棘手的部分是我找不到任何关于如何使用gradle的DSL变量引用测试类路径的引用(即。,android.sourceSets.test.output)。使用这条相对路径看起来很合理。

在引用项目中,必须添加一行:

testCompile project(path: ':volley', configuration: 'tests')

答案 1 :(得分:1)

Tomek Jurkiewicz提到的 Android + Kotlin 解决方案如下:

task jarTests(type: Jar, dependsOn: "assembleDebugUnitTest") {
    getArchiveClassifier().set('tests')
    from "$buildDir/tmp/kotlin-classes/debugUnitTest"
}

configurations {
    unitTestArtifact
}

artifacts {
    unitTestArtifact jarTests
}

将要使用依赖项的项目的等级:

testImplementation project(path: ':shared', configuration: 'unitTestArtifact')