Android Espresso:检查向上导航按钮不可见
Android Espresso: check the navigate up button is not visible
我在 Activity 中有以下工具栏,其中包含两个片段:
当我导航到第二个片段时,有一个向上按钮显示,当返回时,它不在那里,这是正确的。
我只想断言 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))
)
)
)
知道如何断言它才能正常工作吗?
提前致谢!
假设您的原始代码 returns 是 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
}
}
我还建议为该按钮分配一个 id
,因为您找到它的方式非常脆弱。通过 id
查找也可以让您使用 doesNotExist()
.
我在 Activity 中有以下工具栏,其中包含两个片段:
当我导航到第二个片段时,有一个向上按钮显示,当返回时,它不在那里,这是正确的。
我只想断言 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))
)
)
)
知道如何断言它才能正常工作吗?
提前致谢!
假设您的原始代码 returns 是 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
}
}
我还建议为该按钮分配一个 id
,因为您找到它的方式非常脆弱。通过 id
查找也可以让您使用 doesNotExist()
.