Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28541

Find view within hierarchy with Android Espresso

I have a dashboard with custom views.

I want to test that once the data is available, it properly gets displayed in the various text views.

My problem is: how do I select the various TextViews given they belong to a hierarchy.

Example: how to get current_month > sales > value view?

I know only how to do with a single hierarchy level but that does not help here:

onView(
  allOf(withId(R.id.value), 
  isDescendantOfA(withId(R.id.current_month))))

The hierarchy looks like:

+- RelativeLayout
|
|___+ CustomCardView (id = current_month)
|   |
|   |___+ CustomValueView (id = sales)
|   |   |
|   |   |___+ TextView (id = value)
|   |   |
|   |   |___+ TextView (id = unit)
|   |
|   |___+ CustomValueView (id = earnings)
|       |
|       |___+ TextView (id = value)
|       |
|       |___+ TextView (id = unit)
|
|___+ CustomCardView (id = last_month)
|   |
|   |___+ CustomValueView (id = sales)
|   |   |
|   |   |___+ TextView (id = value)
|   |   |
|   |   |___+ TextView (id = unit)
|   |
|   |___+ CustomValueView (id = earnings)
|       |
|       |___+ TextView (id = value)
|       |
|       |___+ TextView (id = unit)
|
|___+ CustomCardView (id = all_time)
    |
    |___+ CustomValueView (id = sales)
    |   |
    |   |___+ TextView (id = value)
    |   |
    |   |___+ TextView (id = unit)
    |
    |___+ CustomValueView (id = earnings)
        |
        |___+ TextView (id = value)
        |
        |___+ TextView (id = unit)

Upvotes: 8

Views: 5336

Answers (2)

Akshay Mahajan
Akshay Mahajan

Reputation: 2190

Use withParent(Matcher) Hierarchy View Matcher:

onView(allOf(withId(R.id.value),
     withParent(allOf(withId(R.id.sales),
          withParent(withId(R.id.current_month)))),
  isDisplayed()));

Hope this helps.

Upvotes: 2

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28541

Ok. Looks rather simple.

    onView(allOf(withId(R.id.value),
            isDescendantOfA(allOf(withId(R.id.sales),
                    isDescendantOfA(withId(R.id.current_month))))))

Is that the best way?

Upvotes: 13

Related Questions