Espresso - how to get current activity for testing fragments?

I have been playing with tests Espressofor a couple of weeks, and I finally decided to start testing the fragments.

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

My application uses data from the login, so I can not start the action using the test rule. Simply put, is there something similar to getActivity()when doing espresso tests?

+4
source share
1 answer

I usually get it like this, it looks (and probably has) hacks, but hey, it works

import static android.support.test.InstrumentationRegistry.getInstrumentation;

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] = it.next();
            }
        });

        return currentActivity[0];
    }
}
+13
source

Source: https://habr.com/ru/post/1650000/


All Articles