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())
I think you can do the following.
onView(withId(android.R.id.home)).perform(click())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With