Show navigation Hide navigation

Testing UI for a Single App

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 AndroidJUnitRunner test runner.

Set Up Espresso

Before you begin using Espresso, you must:

  • Install the Android Testing Support Library. The Espresso API is located under the com.android.support.test.espresso package. These classes allow you to create tests that use the Espresso testing framework. To learn how to install the library, see Testing Support Library Setup.
  • Set up your project structure. In your Gradle project, the source code for the target app that you want to test is typically placed under the app/src/main folder. The source code for instrumentation tests, including your Espresso tests, must be placed under the app/src/androidTest folder. To learn more about setting up your project directory, see Managing Projects.
  • Specify your Android testing dependencies. In order for the Android Plug-in for Gradle to correctly build and run your Espresso tests, you must specify the following libraries in the build.gradle file of your Android app module:
    dependencies {
        androidTestCompile 'com.android.support.test:runner:0.3'
        androidTestCompile 'com.android.support.test:rules:0.3'
        androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2'
    }
    
  • Turn off animations on your test device. Leaving system animations turned on in the test device might cause unexpected results or may lead your test to fail. Turn off animations from Settings by opening Developing Options and turning all the following options off:
    • Window animation scale
    • Transition animation scale
    • Animator duration scale

Create an Espresso Test Class

To create an Espresso test, create a Java class or an ActivityInstrumentationTestCase2 subclass that follows this programming model:

  1. Find the UI component you want to test in an Activity (for example, a sign-in button in the app) by calling the onView() method, or the onData() method for AdapterView controls.
  2. Simulate a specific user interaction to perform on that UI component, by calling the ViewInteraction.perform() or 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 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 ActivityInstrumentationTestCase2 to create your Espresso test class, you must inject an Instrumentation instance into your test class. This step is required in order for your Espresso test to run with the AndroidJUnitRunner test runner.

To do this, call the injectInstrumentation() method and pass in the result of 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, InstrumentationTestRunner would inject the 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 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 onView() method returns a ViewInteraction object that allows your test to interact with the view. However, calling the onView() method may not work if you want to locate a view in an AdapterView layout. In this case, follow the instructions in Locating a view in an AdapterView instead.

Note: The 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 NoMatchingViewException.

The following code snippet shows how you might write a test that accesses an 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:

  • Calling methods in the ViewMatchers class. For example, to find a view by looking for a text string it displays, you can call a method like this:
    onView(withText("Sign-in"));
    

    Similarly you can call withId() and providing the resource ID (R.id) of the view, as shown in the following example:

    onView(withId(R.id.button_signin));
    

    Android resource IDs are not guaranteed to be unique. If your test attempts to match to a resource ID used by more than one view, Espresso throws an AmbiguousViewMatcherException.

  • Using the Hamcrest Matchers class. You can use the allOf() methods to combine multiple matchers, such as containsString() and instanceOf(). This approach allows you to filter the match results more narrowly, as shown in the following example:
    onView(allOf(withId(R.id.button_signin), withText("Sign-in")));
    

    You can use the not keyword to filter for views that don't correspond to the matcher, as shown in the following example:

    onView(allOf(withId(R.id.button_signin), not(withText("Sign-out"))));
    

    To use these methods in your test, import the org.hamcrest.Matchers package. To learn more about Hamcrest matching, see the Hamcrest site.

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 TextView instance.

Locating a view in an AdapterView

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

Instead, call the onData() method to obtain a 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 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 NoMatchingViewException.

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

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

Performing Actions

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

The 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 ViewAction objects. You can specify such actions as:

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

Verifying Results

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

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

  • doesNotExist: Asserts that there is no view matching the specified criteria in the current view hierarchy.
  • matches: Asserts that the specified view exists in the current view hierarchy and its state matches some given Hamcrest matcher.
  • selectedDescendentsMatch : Asserts that the specified children views for a parent view exist, and their state matches some given Hamcrest matcher.

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 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 AndroidJUnitRunner class provided in the Android Testing Support Library as your default test runner. The Android Plug-in for Gradle provides a default directory (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 AndroidJUnitRunner as the default test instrumentation runner in your build.gradle file:
    android {
        defaultConfig {
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
    }
  2. Run your tests from the command-line by calling the the connectedCheck (or cC) task:
    ./gradlew cC