Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 782
Larissa Ford Avatar asked Oct 21 '20 21:10

Larissa Ford


2 Answers

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())
like image 182
Larissa Ford Avatar answered Oct 12 '22 08:10

Larissa Ford


I think you can do the following.

onView(withId(android.R.id.home)).perform(click())
like image 35
Reaz Murshed Avatar answered Oct 12 '22 07:10

Reaz Murshed