The basics of automation are pretty simple:
First we launch an activity, then we find a View, and finally we perform an action on that View (such as a click), or we check something (for example if the View contains a certain text).

The TestRule takes care of launching the Activity for us. After that it is our responsibility to write a good test. Before we’re going to write a whole test, I will show you how to find the Views that we need in our tests in order to perform actions and check things.

Layout Inspector

Android Studio offers us a nice tool that allows us to find the Views that we need. To use it:

  • Launch the app from Android Studio by pressing the green play button in the top right. Make sure ‘app’ is selected from the drop down menu;
Press the green play button on the right
  • Use the app to navigate to the screen you would like to inspect;
  • Launch the Layout Inspector from the Tools menu:
The place to find the Layout Inspector
  • Select the device and activity you would like to inspect;
  • After launching the Layout Inspector you should be greeted by a screen that consists out of three parts. On the left you will see the View Hierarchy. This shows all the nested views, their type, IDs and text if they contain any. In the middle you will see a visual representation of the UI. You can also use this to select specific Views. On the right you can take a look at additional properties for the View that you’ve selected.
The Layout Inspector
  • If you’d like to inspect a different screen, use your device to navigate there, and launch the Layout Inspector from the Tools menu (again).

Exercise 1: Dismiss the onboarding screen

In the first exercise we are going to revisit the test code in the EspressoWorkshopTest class. In the dismissOnboarding method we are going to locate the ‘X’ in the top left of the onboarding screen, so that we can click and dismiss it. Then we will locate a TextView that we expect to find on the custom order screen. These are marked with a red box in the screenshots below.

The only problem is, that the IDs used in the dismissOnboarding test method are wrong. Now it is up to you to find the right IDs and replace the ‘example_id’ and ‘another_example_id’.

onView(withId(R.id.example_id)).perform(click());     
onView(withId(R.id.another_example_id)).check(matches(withText("Customize your order")));

The IDs that we are using start with a ‘R.id’ prefix. If you would like to know why, read my blog post on IDs: App Terminology for Testers: IDs.

To check if your test works, press the green ‘play’ button on the left side of the test method. Pick the ‘Run’ option and select a device or emulator.

The solution can be found at GitHub:
Solution Exercise 1


Continue with part 3: Espresso Core API