Android Studio无法解析org.junit
我正在Android Studio 1.2.2中使用JUnit测试。测试运行没有问题。唯一让我困惑的是Android Studio无法解析实际的org.junit包。显然,它确实解决了这个问题,否则测试将无法运行。但是导入和注释在Android Studio中标记为红色,如下所示。这是Android Studio中的一个bug吗?我尝试重建应用程序并重新启动Android Studio,但这并不能解决问题Android Studio无法解析org.junit,android,android-studio,junit,Android,Android Studio,Junit,我正在Android Studio 1.2.2中使用JUnit测试。测试运行没有问题。唯一让我困惑的是Android Studio无法解析实际的org.junit包。显然,它确实解决了这个问题,否则测试将无法运行。但是导入和注释在Android Studio中标记为红色,如下所示。这是Android Studio中的一个bug吗?我尝试重建应用程序并重新启动Android Studio,但这并不能解决问题 import org.junit.Test; import static org.jun
import org.junit.Test;
import static org.junit.Assert.*; // cannot resolve symbol 'junit'
public class CanadaTest
{
@Test
public void testCountryName() throws Exception
{
int x = 0;
x++;
}
}
尝试
文件->使缓存无效/重新启动
将其放入您的gradle文件:
testCompile 'junit:junit:4.12'
如果上述操作均无效,则可能是您的测试类位于错误的目录中 我遇到这个问题是因为我的文本类位于
/main/java
目录中,而不是它们应该位于的/test
目录中
简而言之:
确保您的测试类位于
/test
目录中 如果您重新安装了android studio,请记住默认情况下它没有使用您的系统JDK(项目结构->SDK位置->JDK位置)。我遇到了这个问题,结果证明这只是因为我将构建变量设置为“release”。当我把它改回“debug”时,androidstudio进行了一次构建,当它完成后,junit注释上的红色错误消失了。
我通过结合一些答案和一些变化来解决这个问题: 1.确保设置prepare
targetSdkVersion
,compileSdkVersion
和buildToolsVersion
2.我使用了上一个Android Gradle插件版本
和Gradle版本
3.在应用程序级别的buil.gradle中添加一些行(我用“\*”标记它们):
4.build.gradle在项目级别上如下所示:
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
apply plugin: 'java' //*
}
}
allprojects {
repositories {
jcenter()
google()
maven {
url "https://jitpack.io"
}
}
}
configurations {
debugImplementation.exclude group: "junit", module: "junit"
}
问题
在插装测试(androidTest)中未找到org.junit.*的类和注释。这些类可以在junit测试(test)中找到 解决方案:
将构建变量从版本切换到调试可能在您的gradle文件中,您有如下内容:
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
apply plugin: 'java' //*
}
}
allprojects {
repositories {
jcenter()
google()
maven {
url "https://jitpack.io"
}
}
}
configurations {
debugImplementation.exclude group: "junit", module: "junit"
}
删除所有内容后都会正常工作。在构建变体中,您的测试工件是“单元测试”?是的。如前所述,一切都已正确配置,测试正在运行。如果某个配置不正确,测试将无法运行,这会引起抱怨。请尝试“使缓存无效并重新启动”有史以来最短的回答。发布
build.gradle
文件。您应该将其放入testCompile
进行单元测试。使用androidTestCompile
instrumentation tests.yup刚刚想给它一个try@JaredBurrows这应该是一个答案。解决了我的错误。谢谢。testCompile现在已经过时了,对于较新的项目,这可能会有所帮助:“配置'testCompile'已经过时,并已被'testImplementation'和'testApi'所取代。”“使用testImplementation'junit:junit:4.12'
就像testCompile
已经过时一样,谢谢您,因为我错误地把它放在单元测试目录中,这真的节省了我的时间。这对我来说也是如此,而且有点道理。任何有建筑护理经验的人都可以解释原因。谢谢兄弟,我欠你一个!