【问题标题】:How do you test the action bar back button with espresso?您如何使用 espresso 测试操作栏后退按钮?
【发布时间】:2021-02-04 20:21:48
【问题描述】:

我正在尝试学习如何测试我的 Android 项目,包括我的导航。我已经实现了一个 navHost 片段作为 NavController,并使用它来设置我的操作栏后退按钮以在我的片段中移动。我不知道如何访问这个后退按钮,以便我可以通过 espresso 对其进行测试。

这是来自主活动的 onCreate 函数的相关代码:

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

这是一个相关的 stackoverflow 页面,但他们询问的是主页按钮,我正在尝试使用后退按钮:How do I test the home button on the Action Bar with Espresso?

这是我目前的测试(我的安卓应用是用来点三明治的):

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

我对 Android 和测试都是新手,因此我们将不胜感激。

【问题讨论】:

    标签: android android-studio kotlin android-fragments android-espresso


    【解决方案1】:

    在检查自动浓缩咖啡测试后,如果语言环境是英语,这是我发现的有效答案:

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

    如果应用程序是多语言的,那么使用:

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

    【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这不起作用,因为它返回了这个错误:androidx.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with id is <android:id/home> 我假设这是因为我没有启用主页按钮。
    • 是的,您可以尝试在您的ToolBar 中设置以下内容,然后再次检查吗?谢谢! toolbar.setDisplayHomeAsUpEnabled(true)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 2021-11-12
    • 1970-01-01
    • 2015-07-02
    相关资源
    最近更新 更多