I am trying to check to see if a view is displayed with Espresso. Here is some pseudo code to show what I am trying:
if (!Espresso.onView(withId(R.id.someID)).check(doesNotExist()){
// then do something
} else {
// do nothing, or what have you
}
But my problem is .check(doesNotExist())
does not return boolean. It is just an assertion. With UiAutomator I was able to just do something like so:
if (UiAutomator.getbyId(SomeId).exists()){
.....
}
Conditional logic in tests is undesirable. With that in mind, Espresso's API was designed to guide the test author away from it (by being explicit with test actions and assertions).
Having said that, you can still achieve the above by implementing your own ViewAction and capturing the isDisplayed check (inside the perform method) into an AtomicBoolean.
Another less elegant option - catch the exception that gets thrown by failed check:
I think to mimic UIAutomator you can do this:
(Though, I suggest rethinking your approach to have no conditions.)
Also
exists
without branching can be implemented really simple:Though most of the time it's worth checking for
matches(isDisplayed())
anyway.Based on the answer by Dhiren Mudgil, I ended up writing the following method:
I'm using this to help determine which View in a ViewFlipper is currently displayed.
We need that functionality and I ended up implementing it below:
https://github.com/marcosdiez/espresso_clone
I hope it is useful for you.
You check with the below code also. If view is displayed it will click else it will pass on.