Skip to content

Instantly share code, notes, and snippets.

@denyszet
Last active August 6, 2021 09:19
Show Gist options
  • Save denyszet/b1722af5634d381cdc56be7d07d628d2 to your computer and use it in GitHub Desktop.
Save denyszet/b1722af5634d381cdc56be7d07d628d2 to your computer and use it in GitHub Desktop.
ViewAssertion sample that checks that all descendant views with provided id have visibility equal to Visibility.INVISIBLE.
@RunWith(AndroidJUnit4::class)
class SampleTest {
@get:Rule
var activityScenarioRule = ActivityScenarioRule(SampleActivity::class.java)
@Test
fun allCheckBoxesShouldNotBeDisplayed() {
onView(withId(R.id.tasksContainer)).check(descendantsWithIdInvisible(R.id.checkbox))
}
fun descendantsWithIdInvisible(@IdRes id: Int) = DescendantsWithIdInvisibleViewAssertion(id)
class DescendantsWithIdInvisibleViewAssertion(@IdRes id: Int) : ViewAssertion {
private val descendantId = id
private val resourceName = InstrumentationRegistry.getInstrumentation()
.targetContext.resources.getResourceEntryName(descendantId)
override fun check(view: View?, noView: NoMatchingViewException?) {
assertTrue(
"Ancestor view should be present in the hierarchy and displayed but it wasn't",
isDisplayed().matches(view)
)
var visibleViewExist = false
(view as ViewGroup).descendants.forEach { descendantView ->
val matches =
withId(descendantId).matches(descendantView)
.and(withEffectiveVisibility(Visibility.VISIBLE).matches(descendantView))
if (matches) {
visibleViewExist = true
}
}
assertFalse(
"View with id: $resourceName was displayed but it shouldn't.",
visibleViewExist
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment