This is an small example of a common mistake I have seen in different projects and different developers.
Usually we, as developers, try to take the code to the more readable way but keeping steps clear.
But sometimes the steps we take for readability keep us away of the final purpouse. This is an example of it.
When trying to check if a view is or not visible we generally overuse allOf
thinking it will do the match on the conditions we pass to it but surprisingly for some of us this does not work like that.
onView
works like a (and I hope someone can correct me) lazy query for the hierarchy view, it only gets a matcher and tries to match when requested to it.
How do we request it to match? Simple, just call perform
or check
.
What happens if we don't call perform
or check
? Actually, nothing. It only stays with like that. With an empty ViewInteraction
that doesn't have problems because, well, it's just an empty element. No one is messing with it or asking anything, so there's no exception, no error, no warning.
A problem:
- You have an Activity (
MainActivity.kt
) which has a layout (activity_main.xml
) and a test for a viewtvAcMainHello
in the activity. * The view isgone
- In the test we do:
onView(allOf(withId(R.id.tvAcMainHello), isDisplayed()))
- We also try to:
onView(allOf(withId(R.id.tvAcNotMainHello), isDisplayed()))
(note theNot
in the name, this is a different view). - We expect the test to fail in some cases here
- Everything passes without problems… why?
Easy! Just remember what @chiuki has been telling us for (now) years:
onView(ViewMatcher)
.perform(ViewAction)
.check(ViewAssertion);
this means, that our common problem: onView(allOf(withId(R.id.tvAcNotMainHello), not(isDisplayed())))
Should be solved with:
onView(withId(R.id.tvAcNotMainHello).check(not(isDisplayed()))
And the hint in here is:
- Keep your matchers as simple as possible. Remember: KISS
- Remember the three steps:
match -> perform -> check
Here's a video about it: https://www.youtube.com/watch?v=JlHJFZvZyxw
And here is the classic espresso cheat sheet: https://developer.android.com/training/testing/espresso/cheat-sheet
Keep the testing!