9

In my Android application I have Toolbar and need to perform action for tool bar back button click in Espresso. I have tried the following but it does not work

onView(withId(R.id.pageToolbar)).perform(click());

Need to perform its back button click action.

cpt. Sparrow
  • 415
  • 8
  • 22
M.A.Murali
  • 9,988
  • 36
  • 105
  • 182

2 Answers2

11

The ContentDescription didn't work for me, so I had to use:

        onView(allOf(
            instanceOf(AppCompatImageButton::class.java), withParent(withId(R.id.toolbar))
        ))
            .perform(click())

because I have not way to identify it univocally in the hierarchy tree:

+-------->AppCompatImageButton{id=-1, visibility=VISIBLE, width=147, height=147, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, layout-params=androidx.appcompat.widget.Toolbar$LayoutParams@acd01cf, tag=null, root-is-layout-requested=false, has-input-connection=false, x=21.0, y=0.0}
PedroDuran
  • 392
  • 2
  • 8
2

If your app is running in English language, use this:

onView(withContentDescription("Navigate up")).perform(click());

To make it run on any language, use this:

onView(withContentDescription(R.string.abc_action_bar_up_description)).perform(click());

Note that R.string.abc_action_bar_up_description comes from the AppCompat support library.

Also note that there is no other unique id for the 'Arrow Back' button, because Espresso sees it as this:

+------> AppCompatImageButton {id=-1, desc=Navigate up, visibility=VISIBLE,
    width=84, height=68, has-focus=false, has-focusable=false, has-window-focus=true,
    is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true,
    is-layout-requested=false, is-selected=false,
    layout-params = android.support.v7.widget.Toolbar$LayoutParams@1af06e3d,
    tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0}
Mr-IDE
  • 7,051
  • 1
  • 53
  • 59