Espresso wait for activity

2 March 2020 Stephan Petzl Leave a comment Tech-Help

Espresso is aware that it needs to wait with assertions and view interactions until an activity is launched and displayed on the screen. So there is nothing special to consider for you.

By default, Espresso waits for UI events in the current message queue to process and default AsyncTasks* to complete before it moves on to the next test operation. This should address the majority of application/test synchronization in your application.

Here is an example:

// MainActivity.kt:
start_activity_button.setOnClickListener {
    val intent = Intent(context,

This testing code will run just fine:

// LoginTest.kt: 
@Rule @JvmField
val activityRule: ActivityTestRule = ActivityTestRule(,true, false)

fun shouldLoginUser(){

Espresso will know that it needs to wait for the UI thread to get idle BEFORE looking up the view. Thread.sleep does not change that, since it keeps the current thread (the UI thread) busy.

So why does Espresso still fail when waiting for the activity to open?

There are still cases where test execution might fail because the activity was not ready to be checked by Espresso. This can happen if opening the activity is done AFTER some asynchronous process is happening and Espresso is not aware of it. Examples would be a network call or a background calculation on another thread.

Network calls can only be sent on a non-UI thread. A restriction which makes sure that the UI transitions run smoothly while data is fetched from a server.

Learn more about Espresso testing in this overview on Espresso, its use and common challenges.

Like this article? there’s more where that came from!

Leave a Reply