user3050720 user3050720 - 10 months ago 79
Android Question

Espresso - how to get current activity to test Fragments?

I have been playing around with

tests for couple weeks now and I finally decided to start testing Fragments.

Immediately I ran into a problem, how do I get current activity?

My app uses data from login so I can't launch the activity with test rule.
Simply put, is there something similar to
when doing espresso tests?

Answer Source

I usually get it like this, it looks (and probably is) hacky but, hey, it works

import static;

public class MyTest {

    private Activity getActivityInstance(){
        final Activity[] currentActivity = {null};

        getInstrumentation().runOnMainSync(new Runnable(){
            public void run(){
                Collection<Activity> resumedActivity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
                Iterator<Activity> it = resumedActivity.iterator();
        currentActivity[0] =;

        return currentActivity[0];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download