首页 > 解决方案 > ActivityScenarioRule 的 Android 测试永远挂起

问题描述

我正在尝试为我的 Android 应用程序编写一个简单的 UI 测试:

@RunWith(AndroidJUnit4::class)
class SimpleTest {

    @get:Rule
    val activityRule = activityScenarioRule<MainActivity>()

    @Test
    fun justPass() {}
}

问题是这个测试永远挂起,应用程序卡在这个屏幕上:

测试卡住时的应用程序屏幕。

它发生在模拟器和真实设备上。完整的标题是androidx.test.core.app.InstrumentationActivityInvoker$EmptyActivity

奇怪的是,如果我按下方形按钮,然后从最近的应用程序中选择相同的屏幕,测试就会完成。

这些是我的测试依赖项:

testImplementation 'junit:junit:4.13.1'
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutines_version"
testImplementation 'android.arch.core:core-testing:2.1.0'
testImplementation "io.mockk:mockk:$mockk_version"
androidTestImplementation 'androidx.test:core-ktx:1.3.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
androidTestImplementation 'androidx.test.ext:junit-ktx:1.1.2'
androidTestImplementation 'androidx.test:runner:1.3.0'
androidTestImplementation "io.mockk:mockk-android:$mockk_version"

如果我添加androidx.test:rules:1.3.0并替换activityScenarioRuleActivityTestRule,测试会按预期自动完成。但是 ActivityTestRule 已被弃用,所以我认为这不是一个好的选择。

那么我应该怎么做才能使这个测试通过而不被卡住呢?

更新

MainActivity 在清单中声明,启动模式为单个实例:

<activity android:name=".MainActivity"
    android:launchMode="singleInstance">
    ... 
</activity>

如果我删除该launchMode属性,测试将不再挂起。尽管如此,应该可以测试具有该属性的活动,所以我仍在寻找解决方案。

标签: androidandroid-testing

解决方案


推荐阅读