How to check the current Activity in a UI test

五迷三道 提交于 2021-01-29 14:08:42

问题


For tests I use Espresso and Barista I have a test in which I need to open another screen by pressing a button. How can I check if this screen opens? Did the screen I need open?

Can I somehow check the chain of screens? To understand that the screens open in the order I need?

If someone throws links to good tutorials on UI tests in Android, I will be very grateful.


回答1:


An easy solution would be to just check for an element of the new screen to be shown like this:

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

If you really want to check out for the current activity that is shown, you could try something like this:

Gather the current activity via InstrumentationRegistry and check for the activity in stage RESUMED.

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
}

You could then check this in a test like this:

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



回答2:


I personally use intended(hasComponent(YourActivityToCheckAgainst::class.java.name)), which checks if the last intent was done with a desired activity, set as its component.

I also wrote an extensive Android UI testing tutorial using Espresso + Barista libraries.



来源:https://stackoverflow.com/questions/60691472/how-to-check-the-current-activity-in-a-ui-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!