Android Espresso - Click checkbox if not checked

前端 未结 5 1018
长情又很酷
长情又很酷 2021-02-18 13:58

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?

5条回答
  •  感情败类
    2021-02-18 14:08

    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.

提交回复
热议问题