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?
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
}
}