UI Autimator
Installation
Section titled “Installation”androidTestImplementation("androidx.test.uiautomator:uiautomator:2.3.0")Before Test Case
Section titled “Before Test Case”- Create a instance for ui automator
private var device = UiDevice.getInstance(getInstrumentation())- Launch the app with shell command
val packageName = "dev.eliashen.goforit"device.pressHome() // >>> Optional: back to home screendevice.executeShellCommand("am start -n $packageName/$packageName.MainActivity")Notice
Section titled “Notice”- 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))}Method with UiObject
Section titled “Method with UiObject”- Select with
Byselector forModifier.testTag("id")
NOTE: If you are using
testTag()with UI Automator, ensure that you addModifier.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
scrollUntilbecause 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 = falseval maxAttempts = 15for (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'")