测试代码未编译并被视为非测试

Ebo*_*ike 5 android android-testing android-studio

我使用自定义测试运行器进行了一些 Android 仪器测试,这些测试似乎都工作正常,直到我升级到 Android Studio 2.1、升级了一些库版本并随着时间的推移做了一些其他事情之后的某个时候。现在,我的测试不再运行Unable to find instrumentation info for: ComponentInfo{}StackOverflow 上已经被问过一百万次的可怕问题了。

经过进一步调查,Android Studio 似乎根本不编译我的测试代码,这意味着它的代码从未包含在内,因此它无法找到测试运行程序的 ComponentInfo。我通过在测试代码中添加编译错误来验证这一点,当我尝试运行测试时,这不会导致任何问题。

此外,测试代码在语法突出显示中似乎被视为非测试代码?例如,测试运行程序导入android.support.test.runner.AndroidJUnitRunner,但runner以红色突出显示,就好像该库丢失一样(但它在 gradle 文件中为androidTestCompile)。如果我将其更改为compile,语法荧光笔会很高兴。但是,测试代码在项目视图中以黄色显示,就像测试代码一样。

我不确定是什么决定了 Android Studio 为测试编译的内容。设置很简单。我的文件层次结构是

app
+--src
+  +--main
+  |  +--java
+  |     +--com/package/files
+  |
+  +--androidTest
+     +--java
+        +--com/package/files
Run Code Online (Sandbox Code Playgroud)

换句话说,有 app/src/main/java/com/... 和 app/src/androidTest/java/com... 主应用程序和测试都使用相同的包。

build.gradle(相关部分):

apply plugin: 'com.android.application'

android {
    compileSdkVersion 'Google Inc.:Google APIs:23'
    buildToolsVersion '24.0.0 rc3'
    defaultConfig {
        multiDexEnabled = true
        applicationId 'com.package'
        minSdkVersion 10
        targetSdkVersion 23
        versionCode 2
        versionName '0.8a'
        signingConfig signingConfigs.release
        testInstrumentationRunner 'com.package.TestRunner'
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
        }
        debug {
            signingConfig signingConfigs.release
        }
    }
    productFlavors {
    }
    dexOptions {
        javaMaxHeapSize "4g"
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }

    lintOptions {
        checkReleaseBuilds true
        abortOnError true
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test:rules:0.5'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
    androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2'
    androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
    androidTestCompile 'com.android.support:support-annotations:23.1.1'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:support-v4:23.1.1'
    [...]
}

apply plugin: 'com.google.gms.google-services'
Run Code Online (Sandbox Code Playgroud)

测试的运行/调试配置也很简单 - 这是一个 Android 测试,仪器运行程序是com.package.TestRunner. 我多次尝试清洁/重建。

Ebo*_*ike 6

答案太尴尬了,我不应该发布它。

我所有模块的“构建变体”都设置为“发布”,因此没有编译任何测试内容。将其设置为“调试”即可解决该问题。如果 Android Studio 能够更加明确地表达这一点,比如在使用发布分片时运行测试时发出警告,那就太好了。