reading_notes

Read: 31 - Espresso

Espresso

Espresso used to write concise, beautiful, and reliable Android UI tests.

Espresso

Example

@Test
public void greeterSaysHello() {
    onView(withId(R.id.name_field)).perform(typeText("Steve")); \\ check the text
    onView(withId(R.id.greet_button)).perform(click()); \\ check the button
    onView(withText("Hello Steve!")).check(matches(isDisplayed())); \\ check if the text display on the screen
}

Espresso tests state expectations, interactions, and assertions clearly without the distraction of boilerplate content, custom infrastructure, or messy implementation details getting in the way.Espresso tests run optimally fast!

Synchronization capabilities

Each time your test invokes onView(), Espresso waits to perform the corresponding UI action or assertion until:

Sample Test (changeText for new Activity)

  @Test
  public void changeText_newActivity() {
    // Type text and then press the button.
    onView(withId(R.id.editTextUserInput)).perform(typeText(STRING_TO_BE_TYPED),
        closeSoftKeyboard());
    onView(withId(R.id.activityChangeTextBtn)).perform(click());
    // support launching a new Activity, so use Espresso Intents to verify intent was sent
    assertThat(Iterables.getOnlyElement(Intents.getIntents())).hasComponentClass(
        ShowTextActivity.class);
  }

Create UI tests with Espresso Test

record espresso

The Espresso Test Recorder tool lets you create UI tests for your app without writing any test code. Espresso Test Recorder then takes the saved recording and automatically generates a corresponding UI test that you can run to test your app.

Record an Espresso test

Espresso tests consist of two primary components: UI interactions(clicking button / writing note) and assertions(verify the existence of button and content of note) on View elements. UI interactions include tap and type actions that a person may use to interact with your app. Assertions verify the existence or contents of visual elements on the screen

Record UI interactions

  1. Click Run > Record Espresso Test.
  2. In the Select Deployment Target window, choose the device on which you want to record the test. Click OK.
  3. Interact with your device to start logging events such as “tap” and “type” actions.

Recorded interactions will appear in the main panel in the Record Your Test window, as shown in figure 1 below. When you run the test, the Espresso test will try executing these actions in the same order.

example

Add assertions to verify UI elements

Assertions verify the existence or contents of a View element through three main types:

To add an assertion to your test, proceed as follows:

The screenshot in figure 2 shows a “text is” assertion being created to verify that the title of the note is “Happy Testing!”: Happy Testing

Save Recording


References