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?
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.
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.
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];
}
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With