Espresso - how to get current activity to test Fragments?

10,705

Solution 1

I usually get it like this, it looks (and probably is) hacky 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];
    }
}

Solution 2

Here is lelloman's solution with a slight change in Kotlin:

import android.app.Activity
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry
import androidx.test.runner.lifecycle.Stage

object EspressoHelper {
    fun getCurrentActivity(): Activity? {
        var currentActivity: Activity? = null
        getInstrumentation().runOnMainSync { run { currentActivity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED).elementAtOrNull(0) } }
        return currentActivity
    }
}
Share:
10,705
user3050720
Author by

user3050720

Updated on June 06, 2022

Comments

  • user3050720
    user3050720 almost 2 years

    I have been playing around with Espresso 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 getActivity() when doing espresso tests?

  • Morozov
    Morozov over 7 years
    but how use this solve? for example now i used like this : val activity = mActivityTestRule.getActivity() val idlingResource = ElapsedTimeIdlingResource(activity)
  • lelloman
    lelloman over 7 years
    I'm afraid I didn't understand your problem
  • Morozov
    Morozov over 7 years
    Sorry for my english) i mean how i can call yours method in another class?
  • lelloman
    lelloman over 7 years
    you just add this method to your class :)
  • Morozov
    Morozov over 7 years
    For example MyTest.getActivityInstance() doesn t work(