Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a button isn't clickable with Espresso

Doing

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

is useful for verifying if a button is clickable. How would I verify that a button isn't clickable?

Edit: Like I said, it only tells me if it isClickable. I'm looking for a way to verify it IS NOT clickable.

like image 422
Nxt3 Avatar asked Apr 10 '16 22:04

Nxt3


People also ask

How do I check if a checkbox is checked in espresso?

You can check this by: onView(withId(R. id. checkbox)).

How do you check the visibility of an element in an espresso machine?

One simple way to check for a View or its subclass like a Button is to use method getVisibility from View class. I must caution that visibility attribute is not clearly defined in the GUI world. A view may be considered visible but may be overlapped with another view, for one example, making it hidden.


1 Answers

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.

It's as simple as: not( isClickable() )

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


Explanation -

I was trying to use the matches or check functions to test the falsity of the matcher they were passed, and that is not possible. It is possible however, to create a matcher which has the opposite logic of another matcher, with the not() function.

After reading the documentation on ViewAssertions (like matches), you find that most ViewAssertions don't accept parameters (and none accept parameters we care about in this case), and must "Throw junit.framework.AssertionError when the view assertion does not hold.". This means we can't change how a ViewAssertion works, we have to find another way.


Breaking down the code -

The onView function returns the UI object we want to work with (the button with the id of login_button), and we call check on that view object to apply an assertion, or check that some assertion is true.

The matches function returns an assertion that we build by passing in a Matcher. The isClickable() function returns to us a Matcher that we can use to give back to matches().

not() is a Matcher which accepts another Matcher, and returns a Matcher which has the opposite logic/return value of the Matcher passed to it. (That's a mouthful!)

This boils down to saying that we apply an assertion to the login_button. The assertion we apply is matches( not( isClickable() ) ).


As a ViewAssertion (matches(not(isClickable()))) is applied (onView(...).check(...)) to a view object (login_button), the action will be logged to logcat and if the assertion is evaluated to false then an AssertionError will also be thrown.

like image 58
Matt C Avatar answered Sep 20 '22 22:09

Matt C