编写Gradle脚本以运行Eclipse Android Test项目的单元测试用例

Chw*_*eet 8 eclipse android gradle

我有一个简单的HelloWorld Android项目(内置在Eclipse IDE中),我能够在cmd提示符下为此项目成功执行"gradle build".

我也为它编写了一个简单的JUnit Android测试项目,它在Eclipse中运行良好.

现在我想使用Gradle脚本运行此测试项目或单元测试用例(如果我的理解是错误的!).我怎么做?

以下是我正在使用的build.gradle文件.我想知道如何编写脚本代码来自动执行测试用例.

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.10.+'
    }
}
apply plugin: 'android'

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

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.3"

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
        test {
            java.srcDirs = ['src/test/java']
            resources.srcDirs = ['src/test/resources']         
        }

        // Move the tests to tests/java, tests/res, etc...
        instrumentTest.setRoot('tests')
        androidTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}
Run Code Online (Sandbox Code Playgroud)

mbm*_*bmc 0

这是我使用的:

android {
    // ...
    // your stuff
    // ...

    // So Android Studio can nicely edit the test files
    sourceSets {
        androidTest {
            java.srcDir file('src/test/java')
        }
    }
}

// <Task to run tests>
sourceSets {
    unitTest {
        java.srcDir file('src/test/java')
    }
}

configurations {
    unitTestCompile.extendsFrom runtime
    unitTestRuntime.extendsFrom unitTestCompile
}

task unitTest(type: Test, dependsOn: assemble) {
    description = "run unit tests"
    testClassesDir = project.sourceSets.unitTest.output.classesDir
    classpath = project.sourceSets.unitTest.runtimeClasspath
}

check.dependsOn unitTest
// </Task to run tests>

dependencies {
    // ...
    // compile stuff
    // ....

    unitTestCompile files("$project.buildDir/classes/release")
    unitTestCompile 'junit:junit:4.11'
 }
Run Code Online (Sandbox Code Playgroud)

运行你的测试:

gradlew unitTest
Run Code Online (Sandbox Code Playgroud)