Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a view from within Espresso to pass into an IdlingResource?

Tags:

I essentially have a custom IdlingResource that takes a View a constructor argument. I can't find anywhere that really talks about how to implement it.

I'm trying to use this answer: https://stackoverflow.com/a/32763454/1193321

As you can see, it takes a ViewPager, but when I'm registering the IdlingResource in my test class, I'm not sure how I can get my view.

I've tried findViewById() and I've tried getting the currently running activity and then calling findViewById() on that, with no luck.

Anyone know what to do in this scenario?

like image 551
EGHDK Avatar asked Jan 08 '16 18:01

EGHDK


People also ask

How do I get the view in espresso test?

Espresso uses onView (Matcher<View> viewMatcher) method to find a particular view among the View hierarchy. onView() method takes a Matcher as argument. Espresso provides a number of these ViewMatchers which can be found in the Espresso Cheat sheet.

What is idling resources in espresso?

An idling resource represents an asynchronous operation whose results affect subsequent operations in a UI test. By registering idling resources with Espresso, you can validate these asynchronous operations more reliably when testing your app.


2 Answers

Figured it out. To get the view to pass into an idling resource, all you have to do is take the member variable of your ActivityTestRule

For example:

@Rule public ActivityTestRule<MainActivity> activityTestRule = new ActivityTestRule<>(         MainActivity.class); 

and then just call getActivity().findViewById(R.id.viewId)

So the end result is:

activityTestRule.getActivity().findViewById(R.id.viewId); 
like image 186
EGHDK Avatar answered Sep 23 '22 14:09

EGHDK


The accepted answer works as long as a test is running in the same activity. However, if the test navigates to another activity activityTestRule.getActivity() will return the wrong activity (the first one). To address this, one can create a helper method returning an actual activity:

public Activity getCurrentActivity() {     final Activity[] currentActivity = new Activity[1];     InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {         @Override         public void run() {             Collection<Activity> allActivities = ActivityLifecycleMonitorRegistry.getInstance()                     .getActivitiesInStage(Stage.RESUMED);             if (!allActivities.isEmpty()) {                 currentActivity[0] = allActivities.iterator().next();             }         }     });     return currentActivity[0]; } 

And then it could be used as the following:

Activity currentActivity = getCurrentActivity(); if (currentActivity != null) {     currentActivity.findViewById(R.id.viewId); } 
like image 37
Anatolii Avatar answered Sep 22 '22 14:09

Anatolii