英文:
Android Espresso: check the navigate up button is not visible
问题
我在一个带有两个片段的活动中有以下工具栏:
当我导航到第二个片段时,会显示一个向上按钮,但当返回时,它不再显示,这是正确的。
我只想用Espresso
来断言它不在那里。为了断言它在那里,我使用了以下代码:
// 导航向上按钮应该显示为工具栏的子项
onView(allOf(instanceOf(AppCompatImageButton::class.java))).check(
matches(
ViewMatchers.withParent(
withId(R.id.toolbar)
)
)
)
然而,我尝试否定它,并尝试以下方式来断言它不显示,但不起作用:
// 导航向上按钮不应该显示为工具栏的子项
onView(Matchers.anyOf(Matchers.instanceOf(AppCompatImageButton::class.java))).check(
matches(
Matchers.not(
withParent(withId(R.id.toolbar))
)
)
)
有没有关于如何断言它以使其起作用的想法?
非常感谢!
英文:
I have the following toolbar in an Activity with two fragments:
When I navigate to the second fragment, there is an up button showing, and when coming back, it isn't there, which is correct.
I just want to assert that it is NOT there with Espresso
. To assert that it is there, I have used:
// 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)
)
)
)
However, I tried to negate it and do the following to assert that it isn't shown, but it doesn't work:
// 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))
)
)
)
Any idea about how to assert it so that it works?
Thanks a lot in advance!
答案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
}
}
我还建议为该按钮分配一个id
,因为您查找按钮的方式相当脆弱。通过id
查找还可以让您使用doesNotExist()
。
英文:
Assuming your original code returns a NoMatchingViewException
when the button doesn't exist, I'd wrap that in a try/catch. I'm simplifying my code below - you'd probably want to make this generic and parameterized for reuse.
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
}
}
I'd also suggest getting an id
assigned to that button because the way you're finding it is pretty brittle. Finding by id
would also let you use doesNotExist()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论