Search code examples
androidkotlinandroid-espressoandroid-uiautomatorandroid-instrumentation

Set app as default button interaction with UI automator


I have a test case where in the app "Set as default" prompt is opened. I want to test that with UI automator, and I had success with testing that case, but not 100% reliable. Unfortunately, some devices have "Set as default" prompt button written in caps, and some of those don't, so I'm not able to create 100% reliable tests for this test case. I have written this code below, but when fetching "Set as default" button by text, case of the letters don't play a role, but when I want to interact with that button, text case is important. Switching the IF-ELSE cases doesn't fix the problem in this case. And somehow, none of the dialog buttons ids work (button1, button2..) when I want to press those.

if (roleManager.isRoleAvailable(android.app.role.ASSISTANT)) {
    if (!roleManager.isRoleHeld(android.app.role.ASSISTANT)) {
        val myApp = device.findObject(UiSelector().textMatches(InstrumentationRegistry.getInstrumentation().targetContext.getString(R.string.app_name)))
        myApp.click()
        sleepLong()
        var setAsDefaultButton: UiObject? = null
        if (device.findObject(UiSelector().text("Set as default")) != null) {
            setAsDefaultButton = device.findObject(UiSelector().text("Set as default"))
            setAsDefaultButton?.click()
        } else if (device.findObject(UiSelector().text("SET AS DEFAULT")) != null) {
            setAsDefaultButton = device.findObject(UiSelector().text("SET AS DEFAULT"))
            setAsDefaultButton?.click()
        } else {
            clickDialogPositiveButton()
        }
    }
}

Solution

  • Based on the Jordan's example and hint, solution to this is to find an object with the Pattern. With pattern, you can search for UIObject with By.text(pattern). Take a note that the object found with the pattern needs to be UIObject2 instead of the UIObject.

    val pattern = Pattern.compile("Set as the default", Pattern.CASE_INSENSITIVE)
    if(device.findObject(UiSelector().text(pattern.toString())) != null) {
        device.findObject(By.text(pattern)).click()
    }