Monday, 17 August 2020

Espresso tests: Match child view by position within parent

I noticed whilst browsing online that all of the answers to the question "can I match the child at a particular index within a particular parent view" required the definition of a new Matcher class. Whilst it's not a huge deal to define a new Matcher class as and when needed, it's not necessary in this case. You can instead get a handle on a particular child of a particular view by joining up the view matchers offered by Espresso into a method as follows:
/**
 * @param parentViewId the resource id of the parent [View].
 * @param position the child index of the [View] to match.
 * @return a [Matcher] that matches the child [View] which has the given [position] within the specified parent.
 */
fun withPositionInParent(parentViewId: Int, position: Int): Matcher<View> {
    return allOf(withParent(withId(parentViewId)), withParentIndex(position))
}

You can use this method as follows:

onView(
    withPositionInParent(R.id.parent, 0)
).check(
    matches(withId(R.id.child))
)

For more view actions and view matchers like this one, check out the android-test-utils repository.

No comments: