-
Notifications
You must be signed in to change notification settings - Fork 7
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:
- Getting the Instrumentation
val instrumentation: Instrumentation get() = InstrumentationRegistry.getInstrumentation()
- Getting a
UiDevice
val device: UiDevice get() = UiDevice.getInstance(instrumentation)
- Then we need a conversion from resourceId to resource name:
infix fun Resources.nameOf(viewId: Int): String = getResourceName(viewId)
- In order to get the resources, we need an application context:
val appContext: Context get() = InstrumentationRegistry.getInstrumentation().targetContext
- And the resource:
val resource: Resources get() = appContext.resources
- And then to create a UiSelector, by resource id:
fun byIdSelector(viewId: Int): UiSelector = UiSelector().resourceId(resource nameOf viewId)
- Query the UiObject by resource id:
infix fun UiDevice.objectById(viewId: Int): UiObject = findObject(byIdSelector(viewId))
- 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()
}