Verifying Fragments With Espresso

I’ve done some searching to see how I can use Espresso to validate the navigation throughout my app. My typical set-up is one activity encompassing whichever fragments make sense to be managed by that activity (adding additional activities with their own fragments as necessary). In my searching, however, all I was finding were people suggesting I select a View that is displayed within that fragment, and check for its existence.

onView(withId(R.id.some_button)).check(matches(isDisplayed()));

But that seems a little too fragile to me, layouts can change fairly easily as projects progress and so I figured, since there seems to be no way to actually check that the fragment itself is displayed, just give the master layout an id and look for that instead.  I see less chance for that to change than I do a view within it.

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/parent_layout" >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/timer"
        android:id="@+id/some_button"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>
onView(withId(R.id.parent_layout)).check(matches(isDisplayed()));

It’s such a minuscule alteration but I think, how it’s performed currently, this is less likely to fail throughout an app’s evolution.

And if that hasn’t convinced you here’s a picture — 9000 seconds in Paint.

layout-2016-02-04-164407

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation