【问题标题】:Android. @RunWith(AndroidJUnit4.class) - cannot resolve in package "androidTest"安卓。 @RunWith(AndroidJUnit4.class) - 无法在包“androidTest”中解析
【发布时间】:2017-02-22 17:10:32
【问题描述】:

Android Studio 2.2.3

安装 Android 支持存储库 - 版本。 44.0.0

我在 Espresso 的官方网站上进行了所有设置:

https://google.github.io/android-testing-support-library/docs/espresso/setup/index.html

我尝试在 androidTest 包中编写仪器测试 (Espresso)。所以我在文件夹 src/androidTest/java/com/mycompany/

中创建 StringUtilAndroidTest

我的 StringUtilAndroidTest 代码:

 @RunWith(AndroidJUnit4.class)
@LargeTest
public class StringUtilAndroidTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule(MainActivity.class);

    @Test
    public void myTest() {
        assert(true);
    }
}

在我的 build.gradle 中:

   android.defaultconfig {
 testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

我的依赖:

   testCompile 'junit:junit:4.12'
testCompile 'org.hamcrest:hamcrest-library:1.3'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
androidTestCompile 'com.android.support.test:testing-support-lib:0.1

但在 StringUtilAndroidTest 中出现编译错误:

@RunWith(AndroidJUnit4.class)

无法解析符号 RunWith

为什么?

【问题讨论】:

  • 除了将 androidTestCompile 行添加到您的 build.gradle 之外,您还记得在 Java 文件的顶部导入类吗?即import org.junit.runner.RunWith;
  • 导入 org.junit.runner.RunWith; - 无法解析符号“RunWith”

标签: android unit-testing


【解决方案1】:

简短回答:将其添加到您的依赖项中,您就可以了。

androidTestCompile 'junit:junit:4.12'
androidTestCompile 'org.hamcrest:hamcrest-library:1.3'

长答案:

在默认配置中,Android Studio 项目有两个不同的测试“变体”:testandroidTest。前者使用'src/test/java',后者使用'src/androidTest/java'(这是你的场景)。

两者之间有很大区别:androidTest 需要一个模拟器或设备才能运行,而test 不需要。这意味着test 的运行速度要快得多(通常在 IDE 上几秒钟),但它无法访问 Android 框架(如活动、上下文等)。另一方面,androidTest 的运行时间要长得多(更不用说模拟器本身的等待时间),但它确实有 Android 框架(因为它是在一个框架中运行的)。

由于它们是两个独立的变体,因此您还需要分别声明它们的依赖关系。 testCompileandroidTestCompile 每个都只将依赖项添加到他们自己的变体中。要在两者上都使用 JUnit,您必须声明对两者的依赖 - 本质上是“重复”该行。

P.S.:请注意,当您使用 compile 时,会将其添加到所有变体中,因此您不必重复非测试依赖项。

【讨论】:

    【解决方案2】:

    你可能错过了一些依赖。

    //App's dependencies, including test
    compile 'com.android.support:support-annotations:22.2.0'
    
    // Testing-only dependencies
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'junit:junit:4.12'
    
    testCompile 'junit:junit:4.12'
    

    希望这会修复您的代码。

    【讨论】:

    • 我刚刚测试过了。他们确实对我有用。
    猜你喜欢
    • 2015-11-17
    • 2018-11-27
    • 2017-09-06
    • 2015-08-16
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    相关资源
    最近更新 更多