如何在 UI 测试中检查当前 Activity

How to check the current Activity in a UI test

对于测试,我使用 Espresso 和 Barista 我有一个测试,我需要按一个按钮打开另一个屏幕。如何检查此屏幕是否打开?我需要的屏幕打开了吗?

我能以某种方式检查屏幕链吗?了解屏幕按我需要的顺序打开?

如果有人在 Android 中提供指向 UI 测试的好教程的链接,我将不胜感激。

一个简单的解决方案是只检查新屏幕的元素是否显示如下:

onView(withId(R.id.id_of_element_in_your_new_screen)).check(matches(isDisplayed()))

如果您真的想查看当前显示的 activity,您可以尝试这样的操作:

通过 InstrumentationRegistry 收集当前 activity 并检查阶段 RESUMED 中的 activity。

fun getTopActivity(): Activity? {
    InstrumentationRegistry.getInstrumentation().runOnMainSync {
        val resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)
        if (resumedActivities.iterator().hasNext()) {
            resumedActivities.iterator().next()?.let {
                activity = it
            }
        }
    }
    return activity
}

然后您可以在这样的测试中进行检查:

@Test
fun checkForActivity() {
    val currentActivity = getTopActivity()
    assertTrue(currentActivity?.javaClass == YourActivityToCheckAgainst::class.java)
}

我个人使用 intended(hasComponent(YourActivityToCheckAgainst::class.java.name)),它会检查最后一个意图是否使用所需的 activity 设置为它的组件。

我还使用 Espresso + Barista 库编写了广泛的 Android UI testing tutorial