2 March 2020 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, LoginActivity::class.java)
Thread.sleep(2000)
startActivity(intent)
}
This testing code will run just fine:
// LoginTest.kt:
...
@Rule @JvmField
val activityRule: ActivityTestRule = ActivityTestRule(MainActivity::class.java,true, false)
@Test
fun shouldLoginUser(){
activityRule.launchActivity(Intent())
onView(withId(R.id.start_activity_button)).perform(click())
onView(withId(R.id.et_email)).perform(typeText("mytestemail@email.com")).perform(closeSoftKeyboard())
onView(withId(R.id.et_password)).perform(typeText("12345678")).perform(closeSoftKeyboard())
onView(withId(R.id.bt_login)).perform(click())
Intents.intended(IntentMatchers.hasComponent(MainActivity::class.java!!.getName()))
}
Espresso will know that it needs to wait for the UI thread to get idle BEFORE looking up the R.id.et_email 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.