When you read the docs, you will notice that Thread.sleep should be avoided. Still, you might run into situations where you find that your tests fail without a line of Thread.sleep(). This can happen if you are doing background work like fetching data from a server or calculating something on another thread via RxJava or RxKotlin.
In all of those cases you will have to tell Espresso to wait till your data is fetched or your background process is finished.
Thread.sleep is a bad way of handling this situation, because it uses a fixed time to pause. If fetching the data from a server is slower than you initially thought (because of a bad network connection), your test will fail.
So the straight forward way to fix this issue is to add a lot of delay (Thread.sleep()) commands into your code. The downside is: We are wasting precious time which can accumulate to minutes and even hours for bigger test batches.
Make Espresso wait the right way
We covered all of that in different blog posts:
- Espresso how to wait for animations to finish
- Espresso how to wait for network calls
- Espresso how to wait for a view to appear
- Espresso how to wait for an activity