how to write code for Android Toolbar back button action in Espresso
Asked Answered
K

2

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.

Kermis answered 22/11, 2016 at 10:57 Comment(0)
M
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}
Madra answered 23/3, 2020 at 15:31 Comment(2)
This worked for me: onView(first(allOf(instanceOf(AppCompatImageButton.class), withParent(withId(R.id.toolbar))))).perform(click());Paradiddle
What is first??Highborn
A
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}
Affront answered 22/11, 2016 at 11:19 Comment(2)
what it is "Navigate up"? is it default text or what to change?Kermis
onView(withContentDescription(R.string.abc_action_bar_up_description)).perform(click()); That is not a default text if u want change means u will change or declare in string and call from hereAffront

© 2022 - 2024 — McMap. All rights reserved.