Skip to content

02. UIAutomator example

Bajic Dusko edited this page Oct 29, 2018 · 2 revisions

When it comes to supporting the UIAutomator, things are much more complicated comparing to Espresso. Just to get to the querying of UIObject by id there are a couple of steps to make:

  1. Getting the Instrumentation
val instrumentation: Instrumentation get() = InstrumentationRegistry.getInstrumentation()
  1. Getting a UiDevice
val device: UiDevice get() = UiDevice.getInstance(instrumentation)
  1. Then we need a conversion from resourceId to resource name:
infix fun Resources.nameOf(viewId: Int): String = getResourceName(viewId)
  1. In order to get the resources, we need an application context:
val appContext: Context get() = InstrumentationRegistry.getInstrumentation().targetContext
  1. And the resource:
val resource: Resources get() = appContext.resources
  1. And then to create a UiSelector, by resource id:
fun byIdSelector(viewId: Int): UiSelector = UiSelector().resourceId(resource nameOf viewId)
  1. Query the UiObject by resource id:
infix fun UiDevice.objectById(viewId: Int): UiObject = findObject(byIdSelector(viewId))
  1. And finally to query the UiObject by using the UiDevice instance:
fun viewById(viewId: () -> Int): UiObject = device.objectById { viewId() }

So, there is a lot of dance in UiAutomator just to find the UI component by id. Additionally, all actions on UI component (UiObject) are an actual methods inside the UiObject class which is unfortunate when comparing to the Espresso architecture, where the actions on UI component are passed through as ViewAction objects.

In order to have the unified syntax with Espresso, we have to use a object. (kudos to @vuksa):

@Suppress("ClassName")
object click

infix fun click.on(uiObject: UiObject) {
  uiObject.click()
}
Clone this wiki locally