简体   繁体   中英

How do you test the action bar back button with espresso?

I'm trying to learn how to test my Android project including my navigation. I have implemented a navHost fragment as a NavController, and use it to set up my action bar back button for moving through my fragments. I'm not sure how to access this back button so that I can test it through espresso.

Here is the relevant code from the onCreate function from the main activity:

val navController = this.findNavController(R.id.myNavHostFragment)
NavigationUI.setupActionBarWithNavController(this, navController)
appBarConfiguration = AppBarConfiguration(navController.graph)

Here is a related stackoverflow page but they are asking about the home button and I am trying to use the back button: How do I test the home button on the Action Bar with Espresso?

Here is my test so far (my android app is for ordering a sandwich):

@Test
fun testNavigation() {
    //check starting screen
    onView(withId(R.id.welcomeConstraint)).check(matches(isDisplayed()))
    //push button
    onView(withText(R.string.order_now)).perform(click())
    //check next screen
    onView(withId(R.id.order_constraint)).check(matches(isDisplayed()))

 
    //TO-DO: check action bar back button


    //click bread
    onView(withText(R.string.wheat)).perform(click())
    //click sandwich
    onView(withText(R.string.panini)).perform(click())
    //click submit
    onView(withText(R.string.submit)).perform(click())

    //this is an issue: need to click submit twice
    onView(withText(R.string.submit)).perform(click())

    //check next screen
    onView(withId(R.id.recieptConstraint)).check(matches(isDisplayed()))
}

I'm new to both Android and testing, so any help would be appreciated.

Here is the working answer I found if locale is English after checking the automatic espresso testing:

val imageButton = onView(
            Matchers.allOf(
                withContentDescription("Navigate up"),
                isDisplayed()
            )
        )
        
imageButton.perform(click())

If the app is multilingual then use:

val imageButton = onView(
            Matchers.allOf(
                withContentDescription(R.string.abc_action_bar_up_description),
                isDisplayed()
            )
        )
        
imageButton.perform(click())

我认为您可以执行以下操作。

onView(withId(android.R.id.home)).perform(click())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM