Espresso is an open-source framework from Google and an instrumentation-based API that works with the AndroidJUnitRunner test runner. Its main function is that it allows you to execute UI tests on Android apps.
After instrumenting your app, the tool provides an easy way to access the objects and execute actions and validations. Here’s a quick guide to setting up Espresso and writing Espresso tests on devices in Perfecto’s Continuous Quality Lab.
Set up Espresso
To add an Espresso test to your project, you should:
1. Install it by adding the lib to the gradle file:
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1' androidTestCompile 'com.android.support.test:runner:0.4.1'
2. Instrument the app by adding this line to your gradle file:
Building the app with the following configuration will open the Espresso API and you can start writing your tests.
How to write Espresso tests
Espresso commands sync automatically with the UI and wait for the elements to appear on the screen.
The test scenario will consist of the following steps:
- onView(object identifier) — Wait for the element to appear in the UI
- Perform — Execute actions in the element
- Check — Validation
This video shows how to execute the Espresso command on a Perfecto device and how the results are presented in a report.
The test below opens a sample native Calculator app, inputs numeric values and then validates the results. See how it appears on a device underneath the code sample below.
onView(withText("Perfecto Calc:")).check(matches(isDisplayed())); onView(withId(R.id.percentage)).perform(typeText("2")); onView(withId(R.id.number)).perform(typeText("20"),closeSoftKeyboard()); onView(withId(R.id.CalcBT)).perform(click()); onView(withId(R.id.results)).check(matches(withText("10.0"))) onView(withId(R.id.number)).perform(typeText("20"),closeSoftKeyboard());