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

时间:2020-10-21 21:02:04

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

我正在尝试学习如何测试我的Android项目,包括导航。我已经将navHost片段实现为NavController,并使用它来设置我的操作栏后退按钮以遍历片段。我不确定如何访问此后退按钮,以便可以通过浓缩咖啡对其进行测试。

这是主要活动中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?

到目前为止,这是我的测试(我的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()))
}

我是Android和测试领域的新手,所以将不胜感激。

2 个答案:

答案 0 :(得分:2)

这是我在检查自动浓缩咖啡测试后发现的有效答案:

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

答案 1 :(得分:1)

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

onView(withId(android.R.id.home)).perform(click())
相关问题