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

后端 未结 4 2014
无人及你
无人及你 2021-01-03 20:59

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

4条回答
  •  暖寄归人
    2021-01-03 21:25

    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 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);
    }
    

提交回复
热议问题