This is the third blog post in a small series that’s meant to introduce a bit of Android App development terminology to testers. The previous posts were about Activities and Views. This post is about View IDs.

If you are automating Android apps with Espresso, you’ll be working with IDs as much as possible. They are an easy and relatively robust way of locating Views, because they have less reasons to change than text for example. When referencing IDs in a test we use the following format: “R.id.your-id”. You may be wondering what the “R.id” prefix is all about. In this post I will try to shed a bit of light on where they come from.

Where do the IDs come from?

View Layouts can be created in XML. In the XML layout you have the option to assign IDs to a View. This can come in handy when arranging the Views. For example, you can state that View with ID A should be displayed beneath the View with ID B. You can also use this ID in your code to assign behaviour or properties to a View (such as changing the text for the View with ID A).

A basic example of XML code for two TextViews:

<TextView
    android:id="@+id/thanks_text"
    style="@style/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="32dp"
    android:text="Thanks for placing your order!"
    android:textSize="24sp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/order_details_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="32dp"
    android:text="Order Details"
    android:textSize="16sp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@id/thanks_text" />

The IDs that are created during development in these XML’s are automatically added to the app Resources. This enables us to use these IDs in the whole project, including our tests. That’s why we use “R.id.*” in our tests when we’re referencing an ID. A nice added bonus is that this also enables auto-complete: if you type “R.id.” you will see a list of available IDs. Another benefit is that when IDs are refactored (by using the Android Studio refactor option) during development, they will be changed in the tests as well, without any additional effort.

If you hold the CMD button (CTRL for windows) and click on the ID, you will be taken to the XML layout file where the ID is defined.

Similarly to IDs, it’s good practice to add text that’s used in an app to the String Resources. These can be accessed by using “R.string.*”. You shouldn’t use these resources for text verification though, because that means you’re using the same text that is used to set the text for a View as your expected value: a test that will never fail.


Leave a Reply