How to improve testability of Jetpack Compose apps for UiAutomator
Jetpack Compose (https://developer.android.com/jetpack/compose) is Android’s recommended modern toolkit for building native UI. It simplifies and accelerates UI development on Android with less code. At the same time, testing a UI created with Jetpack Compose is different from testing a “classic” View-based UI. In Compose, only some composables (the building blocks for creating an app in JetPack Compose) emit UI into the UI hierarchy. Compose provides a set of testing APIs to work with elements, which are arranged in a semantic tree and is primarily used for accessibility. It is up to developers to decide what and how much to expose. By default, UI elements are accessible from the UiAutomator framework only by some descriptors (as displayed text). Let’s take a look at the Jetsurvey sample app (https://github.com/android/compose-samples/tree/main/Jetsurvey) with Appium Inspector (https://github.com/appium/appium-inspector).
Elements of the “Sign in as guest” button do not contain any identifiers to avoid XPath when interacting with it. To solve this problem, Compose offers the use of the following steps:
- Add ‘Modifier.testTag‘ with a unique identifier to the desired composite,
- Enable ‘testTagAsResourceId‘ in the hierarchy with the required composite.
Let’s take a look in Appium Inspector at the changes after that.
The element now has an extra attribute “resource-id” with our unique value “sign_in_guest_button“. We can now locate it and interact with it easily from any test automation tool.