Android Espresso ActivityTest 给出 'package android.support.test.rule does not exist'

Android Espresso ActivityTest gives 'package android.support.test.rule does not exist'

我正在使用此演示为 Android 学习 TDD:

https://github.com/NileshJarad/TDD_Demo

我可以 运行 所有单元测试和 Mockito 测试,但是 "activityTests" 失败并出现以下错误:

error: package android.support.test.rule does not exist 
error: package android.support.test.espresso does not exist 
error: package android.support.test.espresso.action does not exist  
error: package android.support.test.espresso.action does not exist  
error: package android.support.test.espresso.action does not exist  
error: package android.support.test.espresso.assertion does not exist   
error: package android.support.test.espresso.matcher does not exist 
error: package android.support.test.espresso.matcher does not exist 
error: package android.support.test.espresso.matcher does not exist 
error: cannot find symbol class ActivityTestRule    
error: cannot find symbol method isDisplayed()  
...

版本是Android9.0API28.

我尝试了 https://www.google.com/search?q=Android+ActivityTest+gives+%27package+android.support.test.rule+does+not+exist%27 中的建议,但它们都引用了我们已有的 app/build.gradle 行:

...
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
...
dependencies {
...    
    testImplementation 'junit:junit:4.12'
    testImplementation 'org.mockito:mockito-core:1.10.19'
    androidTestImplementation 'com.android.support.test:rules:1.0.2'
    androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    androidTestImplementation 'com.android.support.test:testing-support-lib:0.1'
}

我认为您只需要将 "rules" 依赖项更改为 AndroidX 版本:

androidTestImplementation 'androidx.test:rules:1.2.0'

同步项目后,您需要将测试更改为使用 androidx.test.* 而不是 android.support.test.*(您可以通过删除 greyed-out import声明,然后只接受 Android Studio 建议的所有新导入)。

此时,您的测试应该运行!

还有一件事:您现在可以删除测试顶部的注释 class,其中 "AndroidJUnit4" 被标记为已弃用(即划掉):

@RunWith(AndroidJUnit4.class)

According to the documentation@RunWith 现在仅在混合使用 JUnit3JUnit4 时才需要(您的测试不需要)。