Sergei Buvaka
Sergei Buvaka

Reputation: 621

How to check the current Activity in a UI test

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.

Upvotes: 0

Views: 2299

Answers (2)

lomza
lomza

Reputation: 9716

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.

Upvotes: 2

KraffMann
KraffMann

Reputation: 352

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)
}

Upvotes: 2

Related Questions