来自Gradle的Android中的JUnit测试:“包android.test不存在”

时间:2014-02-18 22:03:50

标签: java android unit-testing junit gradle

我不确定如何让我的单元测试通过Gradle运行。我创建了一个unitTest任务,设置了适当的源集和适当的依赖项,但是我收到了错误:

package android.test does not exist

我在另一篇文章中按照说明操作,并将以下内容添加到我的build.gradle:

// Unit tests
sourceSets {
    unitTest {
        java.srcDir file('test')
        resources.srcDir file('test/res')
    }
}

dependencies {
    unitTestCompile files("$project.buildDir/classes/debug")
    unitTestCompile 'junit:junit:4.11'
    unitTestCompile 'com.google.android:android:4.0.1.2'
}

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
}

下面的完整build.gradle:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.4.2'
    }
}

configurations {
    apt
}

apply plugin: 'android'

dependencies {
    compile project(':PullToRefresh')
    compile project(':simple-crop-image-lib')
    compile project(':facebook')
    compile project(':gridlayout')
    compile project(':nineoldandroids')
    compile project(':ViewPagerIndicator')
    compile project(':volley')
    compile fileTree(dir: 'libs', include: '*.jar')
    apt files('compile-libs/androidannotations-2.7.1.jar')
}

android {
    buildToolsVersion '17.0'
    compileSdkVersion 17

    signingConfigs {
        debug {
            storeFile file('keystores/debug.keystore')
        }
    }

    buildTypes {
        debug {}

        ipconfigurable {
            debuggable true
            signingConfig signingConfigs.debug
        }
    }

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

// Unit tests
sourceSets {
    unitTest {
        java.srcDir file('src/test')
        resources.srcDir file('src/test/res')
    }
}

dependencies {
    unitTestCompile files("$project.buildDir/classes/debug")
    unitTestCompile 'junit:junit:4.11'
    unitTestCompile 'com.google.android:android:4.0.1.2'
}

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
}

目录结构:

enter image description here

1 个答案:

答案 0 :(得分:2)

感谢@PerrynFowler,解决方案是将以下行添加到我的unitTestCompile依赖项中:

unitTestCompile 'com.google.android:android-test:4.1.1.4'