Espresso - How to check if one of the view is displayed

It's possible to catch the exceptions raised by Espresso like this:

If you want to test if a view is in hierarchy:

try {
    onView(withText("Button")).perform(click());
    // View is in hierarchy

} catch (NoMatchingViewException e) {
    // View is not in hierarchy
}

This exception will be thrown if the view is not in the hierarchy.

Sometimes the view can be in the hierarchy, but we need to test if it is displayed, so there is another exception for assertions, like this:

try {
    onView(withText("Button")).check(matches(isDisplayed()));
    // View is displayed
} catch (AssertionFailedError e) {
    // View not displayed
}

There are two cases here that you could be trying to cover. The first is if you are checking if the view "is displayed on the screen to the user" in which case you would use isDisplayed()

onView(matcher).check(matches(isDisplayed()));

or the negation

onView(matcher).check(matches(not(isDisplayed())));

The other case is if you are checking if the view is visible but not necessarily displayed on the screen (ie. an item in a scrollview). For this you can use withEffectiveVisibility(Visibility)

onView(matcher).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));

You can use Matchers.anyOf to check if any of the two views are displayed:

onView(
   anyOf(withId(R.id.view_1), withId(R.id.view_2)) 
).check(matches(isDisplayed()));

For the ones looking to check the visibility status for a view; here are some utility functions I use.

fun ViewInteraction.isGone() = getViewAssertion(ViewMatchers.Visibility.GONE)

fun ViewInteraction.isVisible() = getViewAssertion(ViewMatchers.Visibility.VISIBLE)

fun ViewInteraction.isInvisible() = getViewAssertion(ViewMatchers.Visibility.INVISIBLE)

private fun getViewAssertion(visibility: ViewMatchers.Visibility): ViewAssertion? {
    return ViewAssertions.matches(ViewMatchers.withEffectiveVisibility(visibility))
}

And can be used as follows

onView(withId(R.id.progressBar)).isVisible()
onView(withId(R.id.progressBar)).isGone()