Android Espresso:检查向上导航按钮不可见

问题描述 投票:0回答:1

我在带有两个片段的活动中具有以下工具栏:

fragment toolbar

当我导航到第二个片段时,显示了一个向上按钮,而当返回时,它不存在,这是正确的。我只想断言Espresso不存在。要断言它在那里,我用过:

// The navigate up button should be displayed as a child of the toolbar
        onView(allOf(instanceOf(AppCompatImageButton::class.java))).check(
            matches(
                ViewMatchers.withParent(
                    withId(R.id.toolbar)
                )
            )
        )

但是,我试图对其进行否定,然后执行以下操作以断言它没有显示,但是它不起作用:

// The navigate up button should NOT be displayed as a child of the toolbar
        onView(Matchers.anyOf(Matchers.instanceOf(AppCompatImageButton::class.java))).check(
            matches(
                Matchers.not(
                    withParent(withId(R.id.toolbar))
                )
            )
        )

关于如何断言它以使其起作用的任何想法?

非常感谢!

android android-espresso
1个回答
0
投票

假设您的原始代码在按钮不存在时返回NoMatchingViewException,我将其包装在try / catch中。我在下面简化我的代码-您想对其进行参数化以供重用。

private fun toolbarButtonExists(): Boolean {
    try {
        onView(allOf(instanceOf(AppCompatImageButton::class.java))).check(
            matches(
                ViewMatchers.withParent(
                    withId(R.id.toolbar)
                )
            )
        )
        return true
    } catch (e: NoMatchingViewException) {
        return false
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.