Espresso - how to get current activity to test Fragments?
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
}
}
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];
}
}