I have onView(withId(R.id.check_box)).perform(click())
, but i only want to do this if the check box is not already checked. How can I do this in espresso?
I had the same problem an wrote an own ViewAction that always unchecks my SwitchCompat
class UncheckViewAction implements ViewAction{
@Override
public Matcher getConstraints() {
return new Matcher() {
@Override
public boolean matches(Object item) {
return isA(SwitchCompat.class).matches(item);
}
@Override
public void describeMismatch(Object item, Description mismatchDescription) {
}
@Override
public void _dont_implement_Matcher___instead_extend_BaseMatcher_() {
}
@Override
public void describeTo(Description description) {
}
};
}
@Override
public String getDescription() {
return null;
}
@Override
public void perform(UiController uiController, View view) {
SwitchCompat scView = (SwitchCompat) view;
scView.setChecked(false);
}
}
and used it like this:
onView(withId(R.id.check_box)).perform(new UncheckViewAction())
now i can be sure that the found switch is always unchecked, no matter if it was checked or unchecked before.