Android Studio无法找到JUnit包。

3

我似乎无法让测试文件找到Junit4。我已经尝试了很长时间,但仍然感到沮丧。它说无法在org下找到符号junit。我已经搜索了所有的谷歌(几天),甚至安卓文档也说这就是做法。我错在哪里了?

这是我的测试类:

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 设置测试,并且使用了上面列出的 Gradle,它们应该在“test”的子目录中。一个常见的错误是将它们放在“androidTest”子目录中。 - iagreen
它们位于androidTest目录中,当前位置为:app\src\androidTest\java\stuff.morestuffs。让我尝试将它们移动。 - Steve's a D
对于 JVM 上的单元测试,请将它们移动到 app\src\test\java\stuff.morestuffstestCompile 用于 JVM 依赖项,androidTestCompile 用于 DVM(dalvik/on device)单元测试。 - iagreen
@iagreen 我把它们移动到了那个目录,但是Android Studio就是不认识它是一个类/代码文件,在文件上有一个红色(!),而且没有任何代码完成/验证工作...... 有什么建议吗?我已经试了一会儿了,但没有运气...在AS中执行的JVM测试不应该被执行吗? - Steve's a D
你可以从AS中运行它们。请查看此指南--http://tools.android.com/tech-docs/unit-testing-support - iagreen
3
在“构建变体”下,我选择了“Android仪器测试”。当我将其更改为“单元测试”时,Android Studio正确识别了我的文件。一切都很好!谢谢@iagreen! - Steve's a D
2个回答

3
  1. 对于单元测试(JVM 测试),根源代码目录应该是 test,而不是 Android 仪器测试中的 androidTest

  2. 在“构建变体”下,我选择了“Android 仪器测试”。当我将其更改为“单元测试”时,Android Studio 正确地识别了我的文件。


1

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

androidTestCompile 'junit:junit:4.12'

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接