Android Studio 找不到 JUnit 包

Android Studio cannot find JUnit package

我似乎无法找到 Junit4 的测试文件。我一直在努力,我只是很沮丧。它说在 org 下找不到符号 junit。我用谷歌搜索(几天)的所有内容,甚至 android 文档都说这是如何做到的。我做错了什么?

这是我的测试class

import org.junit.Test;
import android.app.Application;



public class ApplicationTest {
  //  @Test
    public ApplicationTest() {


    }
}

这是我的 build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
   //buildToolsVersion "21.1.2"
    buildToolsVersion "22.0.1"
    defaultConfig {
        applicationId "stuff.morestuffs"
        minSdkVersion 19
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile files('libs/gson-2.3.1.jar')
    testCompile 'junit:junit:4.12'
}

这是我的项目build.gradle

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

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

我正在使用 Android Studio 1.4

  1. 对于单元测试(JVM 测试),根源目录应该是 test,而不是 androidTest 作为 Android 仪器测试。

  2. 在 "Build Variants" 下,我选择了 "Android Instrument Tests"。当我将其更改为 "Unit Tests" 时,Android Studio 正确识别了我的文件。

当我向 build.gradle 添加以下依赖项时,我解决了这个问题:

androidTestCompile 'junit:junit:4.12'

如果您需要测试多个单独的方法,并且您想要测试您的 Activity 或片段,则必须添加它。