Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity.findViewById() returns null in Espresso test

In an Espresso test, I want to get reference to my ViewPager so I can attach an IdlingResource to it. But findViewById returns null, even though I confirm just before that the ViewPager is displayed.

// Passes
onView(withId(R.id.viewPager)).check(matches(isDisplayed()));
Activity activity = activityTestRule.getActivity();
assertNotNull(activity);
// Fails
assertNotNull(activity.findViewById(R.id.viewPager));

Any ideas?

like image 763
TBridges42 Avatar asked Jul 20 '16 02:07

TBridges42


1 Answers

You provide not that much information. But lets work with what we have.

I assume the Activity has been started successfully and the DialogFragment (that contains the ViewPager) is displayed too:

The first line of your posted code onView(withId(R.id.viewPager)).check(matches(isDisplayed())); does pass, because Espresso searches trough all views that have been added to the current window. And the dialog is somewhere in the window's layout hierarchy.

But assertNotNull(activity.findViewById(R.id.viewPager)); does fail, because the ViewPager is not in the content view of the Activity but in the FragmentDialog.

You can verify view hierarchy with the help of the Hierarchy Viewer. Compare the hierarchy with and without the dialog.

Why do you want to add an IdlingResource to the ViewPager?

like image 64
thaussma Avatar answered Nov 20 '22 11:11

thaussma