简体   繁体   English

您如何使用 espresso 测试操作栏后退按钮?

[英]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.我正在尝试学习如何测试我的 Android 项目,包括我的导航。 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.我已经实现了一个 navHost 片段作为 NavController,并使用它来设置我的操作栏后退按钮以在我的片段中移动。 I'm not sure how to access this back button so that I can test it through espresso.我不确定如何访问此后退按钮,以便我可以通过 espresso 对其进行测试。

Here is the relevant code from the onCreate function from the main activity:以下是来自主要活动的 onCreate 函数的相关代码:

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?这是一个相关的 stackoverflow 页面,但他们询问主页按钮,而我正在尝试使用后退按钮: 如何使用 Espresso 测试操作栏上的主页按钮?

Here is my test so far (my android app is for ordering a sandwich):到目前为止,这是我的测试(我的 android 应用程序用于订购三明治):

@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.我是 Android 和测试的新手,所以任何帮助将不胜感激。

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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