8 March 2020 Leave a comment Tech-Help
While waiting for a view to show up is usually handled by Espresso itself, there might be cases where your app is doing work on another thread (fetching data from a server, calculating something) and therefore Espresso does not know about it.
Make Espresso wait for the view to show up
There are different ways to handle this, most commonly idling resources. Since we have covered the use and downsides of idling resources in other posts, we want to introduce another way how to go about this problem.
Waiting for a view to show up without the need for an idling resource
A nice way to handle this case is to use ViewActions. ViewActions are responsible for performing an interaction on a given View element.
The ViewAction class is part of the public test framework API which allows devs to write their own ViewAction implementations when necessary.
And then it’s actually quite simple to use:
The official documentation mentions a couple of rules you should follow when implementing ViewActions:
- Inject motion events or key events via the UiController to simulate user interactions.
- Do not mutate the view directly via setter methods and other state changing methods on the view parameter.
- Do not throw AssertionErrors. Assertions belong in ViewAssertion classes.
- View action code will executed on the UI thread, therefore you should not block, perform sleeps, or perform other expensive computations.
- The test framework will wait for the UI thread to be idle both before and after perform() is called. This means that the
- action is guaranteed to be synchronized with any other view operations.
- Downcasting the View object to an expected subtype is allowed, so long as the object expresses the subtype matches the constraints as specified in getConstraints.
Advantages of using ViewActions instead of idling resources
We use ViewActions in favor of Idling resources whenever we can. For the following reasons:
- No need to modify your application code
- ViewActions are more intuitive to use than idling resources
- Easy to use in a generic way (see above: the waitForView ViewAction could be used for all kinds of views)
Make Espresso wait for a text to appear
Since text fields are also just views, you can simply use the ViewAction above to check if the text is on stage. However: If you don’t want to use an ID (or you are not allowed to set an ID on the view), you can use this ViewAction:
Further readings
Learn more about Espresso in this overview on Espresso use and challenges.