Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Espresso - how to get current activity to test Fragments?

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?

like image 273
user3050720 Avatar asked Aug 03 '16 07:08

user3050720


People also ask

Does espresso support test recording?

The Espresso Test Recorder tool lets you create UI tests for your app without writing any test code. By recording a test scenario, you can record your interactions with a device and add assertions to verify UI elements in particular snapshots of your app.

How do you check espresso visibility?

One simple way to check for a View or its subclass like a Button is to use method getVisibility from View class. I must caution that visibility attribute is not clearly defined in the GUI world. A view may be considered visible but may be overlapped with another view, for one example, making it hidden.


Video Answer


2 Answers

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];
    }
}
like image 89
lelloman Avatar answered Oct 15 '22 00:10

lelloman


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
    }
}
like image 26
Oliver Metz Avatar answered Oct 15 '22 00:10

Oliver Metz