Skip to content

UI Autimator

androidTestImplementation("androidx.test.uiautomator:uiautomator:2.3.0")
  1. Create a instance for ui automator
private var device = UiDevice.getInstance(getInstrumentation())
  1. Launch the app with shell command
val packageName = "dev.eliashen.goforit"
device.pressHome() // >>> Optional: back to home screen
device.executeShellCommand("am start -n $packageName/$packageName.MainActivity")
  • Make sure the UI has display properly by using device.wait() method

Wait for the UI to render with a maximum timeout of 5000ms before calling device.findObject()

fun id(id: String): UiObject2 {
device.wait(Until.hasObject(By.res(id)), 5000)
return device.findObject(By.res(id))
}
  • Select with By selector for Modifier.testTag("id")

NOTE: If you are using testTag() with UI Automator, ensure that you add Modifier.semantics { testTagsAsResourceId = true } to the root composable. If there are dialogs that also require testing, add this inside the dialogs as well.

device.findObject(By.res(id))
  • Click .click()
  • Text Input
.text = "Yap! just like this" // <<< The text variable is also a mutable variable, allowing direct changes to update the UI.
  • Scroll until element found. (Note: We check the return value of scrollUntil because this method does not automatically throw an exception if no object matches the description.)
.scrollUntil(
Direction.DOWN,
Until.hasObject(By.textContains("London")) // <<< commom condition syntax in ui automator
).let {
if (!it) throw Exception("NOT_FOUND")
}
// for older version (2.2.0)
val scrollableList = UiScrollable(UiSelector().resourceId("news_list"))
var found = false
val maxAttempts = 15
for (i in 0 until maxAttempts) {
if (device.hasObject(By.textContains("London"))) {
found = true
break
}
scrollableList.scrollForward()
}
if (!found) throw Exception("Could not find news containing 'London'")