Android Espresso - Click checkbox if not checked

前端 未结 5 1102
长情又很酷
长情又很酷 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:16

    Just as @FrostRocket suggested but written in Kotlin.

    We define a custom action that can only performed on checkable items (as specified in constraints). So we safely cast the view to Checkable to access setCheckable method.

    fun setChecked(checked: Boolean) = object : ViewAction {
        val checkableViewMatcher = object : BaseMatcher() {
            override fun matches(item: Any?): Boolean = isA(Checkable::class.java).matches(item)
            override fun describeTo(description: Description?) {
                description?.appendText("is Checkable instance ")
            }
        }
    
        override fun getConstraints(): BaseMatcher = checkableViewMatcher
        override fun getDescription(): String? = null
        override fun perform(uiController: UiController?, view: View) {
            val checkableView: Checkable = view as Checkable
            checkableView.isChecked = checked
        }
    }
    

提交回复
热议问题