使用 Espresso 确定按钮是否不可点击

Determine if a button isn't clickable with Espresso

正在做

onView(withId(R.id.login_button)).check(matches(isClickable()));

可用于验证按钮 是否 可点击。我如何验证按钮 不是 可点击的?

编辑:就像我说的,它只告诉我它是否 isClickable。我正在寻找一种方法来验证它 不是 可点击的。

Edit - Solution!

The solution is to use the not() function which returns a matcher that has the opposite logic of the matcher you pass to it.

就这么简单:not( isClickable() )

onView(withId(R.id.login_button)).check(matches( not(isClickable()) ));


解释-

我试图使用匹配或检查函数来测试它们传递的匹配器的虚假性,但这是不可能的。但是,可以使用 not() 函数创建一个与另一个匹配器具有相反逻辑的匹配器。

看完documentation on ViewAssertions(like matches),你发现大多数ViewAssertions不接受参数(而none接受我们关心的参数在这种情况下),并且必须 "Throw junit.framework.AssertionError when the view assertion does not hold."。这意味着我们无法更改 ViewAssertion 的工作方式,我们必须找到另一种方法。


Breaking down the code -

onView函数returns我们要处理的UI对象(id为login_button的按钮),我们调用check 在该视图对象上应用断言,或 检查 某些断言是否为真。

matches 函数 returns 我们通过传入 Matcher 构建的断言。 isClickable() 函数 returns 给我们一个匹配器,我们可以用它来回馈 matches()

not() 是一个接受另一个匹配器的匹配器,returns 是一个匹配器,它具有传递给它的匹配器的相反 logic/return 值。 (真是一口啊!)

这归结为说我们对 login_button 应用断言。我们应用的断言是 matches( not( isClickable() ) ).


当 ViewAssertion (matches(not(isClickable()))) 应用于 (onView(...).check(...)) 视图对象 (login_button) 时,操作将记录到 logcat,如果断言被评估为 false 然后 AssertionError 也将被抛出。