page.title=Testing UI for a Single App page.tags=testing,espresso trainingnavtop=true @jd:body

Dependencies and Prerequisites

This lesson teaches you to

  1. Set Up Espresso
  2. Create an Espresso Test Class
  3. Run Espresso Tests on a Device or Emulator

You should also read

Try it out

Testing user interactions within a single app helps to ensure that users do not encounter unexpected results or have a poor experience when interacting with your app. You should get into the habit of creating user interface (UI) tests if you need to verify that the UI of your app is functioning correctly.

The Espresso testing framework, provided by the Android Testing Support Library, provides APIs for writing UI tests to simulate user interactions within a single target app. Espresso tests can run on devices running Android 2.2 (API level 8) and higher. A key benefit of using Espresso is that it provides automatic synchronization of test actions with the UI of the app you are testing. Espresso detects when the main thread is idle, so it is able to run your test commands at the appropriate time, improving the reliability of your tests. This capability also relieves you from having to adding any timing workarounds, such as a sleep period, in your test code.

The Espresso testing framework is an instrumentation-based API and works with the {@code AndroidJUnitRunner} test runner.

Set Up Espresso

Before you begin using Espresso, you must:

Create an Espresso Test Class

To create an Espresso test, create a Java class or an {@link android.test.ActivityInstrumentationTestCase2} subclass that follows this programming model:

  1. Find the UI component you want to test in an {@link android.app.Activity} (for example, a sign-in button in the app) by calling the {@code onView()} method, or the {@code onData()} method for {@link android.widget.AdapterView} controls.
  2. Simulate a specific user interaction to perform on that UI component, by calling the {@code ViewInteraction.perform()} or {@code DataInteraction.perform()} method and passing in the user action (for example, click on the sign-in button). To sequence multiple actions on the same UI component, chain them using a comma-separated list in your method argument.
  3. Repeat the steps above as necessary, to simulate a user flow across multiple activities in the target app.
  4. Use the {@code ViewAssertions} methods to check that the UI reflects the expected state or behavior, after these user interactions are performed.

These steps are covered in more detail in the sections below.

The following code snippet shows how your test class might invoke this basic workflow:

onView(withId(R.id.my_view))            // withId(R.id.my_view) is a ViewMatcher
        .perform(click())               // click() is a ViewAction
        .check(matches(isDisplayed())); // matches(isDisplayed()) is a ViewAssertion

Using Espresso with ActivityInstrumentationTestCase2

If you are subclassing {@link android.test.ActivityInstrumentationTestCase2} to create your Espresso test class, you must inject an {@link android.app.Instrumentation} instance into your test class. This step is required in order for your Espresso test to run with the {@code AndroidJUnitRunner} test runner.

To do this, call the {@link android.test.InstrumentationTestCase#injectInstrumentation(android.app.Instrumentation) injectInstrumentation()} method and pass in the result of {@code InstrumentationRegistry.getInstrumentation()}, as shown in the following code example:

import android.support.test.InstrumentationRegistry;

public class MyEspressoTest
        extends ActivityInstrumentationTestCase2<MyActivity> {

    private MyActivity mActivity;

    public MyEspressoTest() {
        super(MyActivity.class);
    }

    @Before
    public void setUp() throws Exception {
        super.setUp();
        injectInstrumentation(InstrumentationRegistry.getInstrumentation());
        mActivity = getActivity();
    }

   ...
}

Note: Previously, {@link android.test.InstrumentationTestRunner} would inject the {@link android.app.Instrumentation} instance, but this test runner is being deprecated.

Accessing UI Components

Before Espresso can interact with the app under test, you must first specify the UI component or view. Espresso supports the use of Hamcrest matchers for specifying views and adapters in your app.

To find the view, call the {@code onView()} method and pass in a view matcher that specifies the view that you are targeting. This is described in more detail in Specifying a View Matcher. The {@code onView()} method returns a {@code ViewInteraction} object that allows your test to interact with the view. However, calling the {@code onView()} method may not work if you want to locate a view in an {@link android.widget.AdapterView} layout. In this case, follow the instructions in Locating a view in an AdapterView instead.

Note: The {@code onView()} method does not check if the view you specified is valid. Instead, Espresso searches only the current view hierarchy, using the matcher provided. If no match is found, the method throws a {@code NoMatchingViewException}.

The following code snippet shows how you might write a test that accesses an {@link android.widget.EditText} field, enters a string of text, closes the virtual keyboard, and then performs a button click.

public void testChangeText_sameActivity() {
    // Type text and then press the button.
    onView(withId(R.id.editTextUserInput))
            .perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard());
    onView(withId(R.id.changeTextButton)).perform(click());

    // Check that the text was changed.
    ...
}

Specifying a View Matcher

You can specify a view matcher by using these approaches:

To improve the performance of your Espresso tests, specify the minimum matching information needed to find your target view. For example, if a view is uniquely identifiable by its descriptive text, you do not need to specify that it is also assignable from the {@link android.widget.TextView} instance.

Locating a view in an AdapterView

In an {@link android.widget.AdapterView} widget, the view is dynamically populated with child views at runtime. If the target view you want to test is inside an {@link android.widget.AdapterView} (such as a {@link android.widget.ListView}, {@link android.widget.GridView}, or {@link android.widget.Spinner}), the {@code onView()} method might not work because only a subset of the views may be loaded in the current view hierarchy.

Instead, call the {@code onData()} method to obtain a {@code DataInteraction} object to access the target view element. Espresso handles loading the target view element into the current view hierarchy. Espresso also takes care of scrolling to the target element, and putting the element into focus.

Note: The {@code onData()} method does not check if if the item you specified corresponds with a view. Espresso searches only the current view hierarchy. If no match is found, the method throws a {@code NoMatchingViewException}.

The following code snippet shows how you can use the {@code onData()} method together with Hamcrest matching to search for a specific row in a list that contains a given string. In this example, the {@code LongListActivity} class contains a list of strings exposed through a {@link android.widget.SimpleAdapter}.

onData(allOf(is(instanceOf(Map.class)),
        hasEntry(equalTo(LongListActivity.ROW_TEXT), is(str))));

Performing Actions

Call the {@code ViewInteraction.perform()} or {@code DataInteraction.perform()} methods to simulate user interactions on the UI component. You must pass in one or more {@code ViewAction} objects as arguments. Espresso fires each action in sequence according to the given order, and executes them in the main thread.

The {@code ViewActions} class provides a list of helper methods for specifying common actions. You can use these methods as convenient shortcuts instead of creating and configuring individual {@code ViewAction} objects. You can specify such actions as:

If the target view is inside a {@link android.widget.ScrollView}, perform the {@code ViewActions.scrollTo()} action first to display the view in the screen before other proceeding with other actions. The {@code ViewActions.scrollTo()} action will have no effect if the view is already displayed.

Verifying Results

Call the {@code ViewInteraction.check()} or {@code DataInteraction.check()} method to assert that the view in the UI matches some expected state. You must pass in a {@code ViewAssertion} object as the argument. If the assertion fails, Espresso throws an {@link junit.framework.AssertionFailedError}.

The {@code ViewAssertions} class provides a list of helper methods for specifying common assertions. The assertions you can use include:

The following code snippet shows how you might check that the text displayed in the UI has the same value as the text previously entered in the {@link android.widget.EditText} field.

public void testChangeText_sameActivity() {
    // Type text and then press the button.
    ...

    // Check that the text was changed.
    onView(withId(R.id.textToBeChanged))
            .check(matches(withText(STRING_TO_BE_TYPED)));
}

Run Espresso Tests on a Device or Emulator

To run Espresso tests, you must use the {@code AndroidJUnitRunner} class provided in the Android Testing Support Library as your default test runner. The Android Plug-in for Gradle provides a default directory ({@code src/androidTest/java}) for you to store the instrumented test classes and test suites that you want to run on a device. The plug-in compiles the test code in that directory and then executes the test app using the configured test runner class.

To run Espresso tests in your Gradle project:

  1. Specify {@code AndroidJUnitRunner} as the default test instrumentation runner in your {@code build.gradle} file:
    android {
        defaultConfig {
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
    }
  2. Run your tests from the command-line by calling the the {@code connectedCheck} (or {@code cC}) task:
    ./gradlew cC