Search code examples
androidandroid-studioandroid-espressoandroid-testinghamcrest

Testing contents of a Relative Layout in Espresso


I have the following Structure:

+------------>LinearLayout{id=2131689635, res-name=ll_monthly_advance_payments_container, 
|
+------------->LinearLayout{id=2131689636,  res-name=ll_monthly_advance_payments_list_container, 
|
+-------------->LeftRightListItemView{id=-1, 
|
+--------------->RelativeLayout{id=-1, 
|
+---------------->ScrollableTextView{id=2131689786, res-name=stv_left, text=Electricity
|
+---------------->AppCompatTextView{id=2131689787, res-name=tv_right, text=53.00 EUR
|
+-------------->LeftRightListItemView{id=-1, 
|
+--------------->RelativeLayout{id=-1, 
|
+---------------->ScrollableTextView{id=2131689786, res-name=stv_left, text=Water
|
+---------------->AppCompatTextView{id=2131689787, res-name=tv_right, text=251.00 EUR
|
+-------------->LeftRightListItemView{id=-1, 
|
+--------------->RelativeLayout{id=-1, 
|
+---------------->ScrollableTextView{id=2131689786, res-name=stv_left, text=Totals
|
+---------------->AppCompatTextView{id=2131689787, res-name=tv_right, text=304.00 EUR

What I am trying to do is test whether as a pair, stv_left and tv_right contains the correct values. I can confirm each one individually with the following script:

onView(allOf(withId(R.id.tv_right), withText("53.00 EUR"), isDescendantOfA(withId(R.id.ll_monthly_advance_payments_list_container))));

I cannot confirm them as a pair. How I can solve this problem?


Solution

  • Do you have a ListView? Then you could use the onData DataInteraction instead of the onView ViewInteraction.

    If this is not feasible you could use the hasSibling Matcher, e.g. in this way:

    onView(allOf(withId(R.id.stv_left), withText("Electricity"),
        hasSibling(allOf(withId(R.id.tv_right), withText("53.00 EUR"))),
        isDescendantOfA(withId(R.id.ll_monthly_advance_payments_list_container))));
    

    But you probably want to do the text matching in the check() like this (I also removed some matchers which don't seem necessary for me):

    onView(allOf(
        withId(R.id.tv_right),
        hasSibling(withText("Electricity"))))
    .check(matches(withText("53.00Euro")));