android.support.test.uiautomator.UiObject Java Examples

The following examples show how to use android.support.test.uiautomator.UiObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UIAnimatorTest.java    From Expert-Android-Programming with MIT License 7 votes vote down vote up
@Test
public void testChangeText_sameActivity() {


    UiObject skipButton = mDevice.findObject(new UiSelector()
            .text("SKIP").className("android.widget.TextView"));

    // Simulate a user-click on the OK button, if found.
    try {
        if (skipButton.exists() && skipButton.isEnabled()) {
                skipButton.click();
        }
    } catch (UiObjectNotFoundException e) {
        e.printStackTrace();
    }
}
 
Example #2
Source File: ItNotificationsManager.java    From SmoothClicker with MIT License 6 votes vote down vote up
/**
 * Inner method to get a dedicated notification and test it
 * @param textContent - The text to use to get the notification
 */
private void testIfNotificationExists( String textContent ) {

    UiObject n = null;

    if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH ){
        n = mDevice.findObject(
                new UiSelector()
                    .resourceId("android:id/text")
                    .className("android.widget.TextView")
                    .packageName("pylapp.smoothclicker.android")
                    .textContains(textContent));
    } else {
        n = mDevice.findObject(
                new UiSelector()
                        .resourceId("android:id/text")
                        .className("android.widget.TextView")
                        .packageName("com.android.systemui")
                        .textContains(textContent));
    }

    mDevice.openNotification();
    n.waitForExists(2000);
    assertTrue(n.exists());

}
 
Example #3
Source File: PermissionGranter.java    From mobile-android-samples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void allowPermissionsIfNeeded() {
    try {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            sleep(PERMISSIONS_DIALOG_DELAY);
            UiDevice device = UiDevice.getInstance(getInstrumentation());
            UiObject allowPermissions = device.findObject(new UiSelector()
                    .clickable(true)
                    .checkable(false)
                    .index(GRANT_BUTTON_INDEX));

            if (allowPermissions.exists()) {
                allowPermissions.click();
            }
        }

    } catch (UiObjectNotFoundException e) {
        System.out.println("There is no permissions dialog to interact with");
    }
}
 
Example #4
Source File: PermissionGranter.java    From mobile-android-samples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void allowPermissionsIfNeeded() {
    try {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            sleep(PERMISSIONS_DIALOG_DELAY);
            UiDevice device = UiDevice.getInstance(getInstrumentation());
            UiSelector selector = new UiSelector()
                    .clickable(true)
                    .checkable(false)
                    .index(GRANT_BUTTON_INDEX);
            UiObject allowPermissions = device.findObject(selector);

            if (allowPermissions.exists()) {
                allowPermissions.click();
            }
        }

    } catch (UiObjectNotFoundException e) {
        System.out.println("There is no permissions dialog to interact with");
    }
}
 
Example #5
Source File: MainActivityTest.java    From android-testing-guide with MIT License 6 votes vote down vote up
@Ignore
@Test
public void testUiAutomatorAPI() throws UiObjectNotFoundException, InterruptedException {
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

    UiSelector editTextSelector = new UiSelector().className("android.widget.EditText").text("this is a test").focusable(true);
    UiObject editTextWidget = device.findObject(editTextSelector);
    editTextWidget.setText("this is new text");

    Thread.sleep(2000);

    UiSelector buttonSelector = new UiSelector().className("android.widget.Button").text("CLICK ME").clickable(true);
    UiObject buttonWidget = device.findObject(buttonSelector);
    buttonWidget.click();

    Thread.sleep(2000);
}
 
Example #6
Source File: ItIntroScreensActivity.java    From SmoothClicker with MIT License 6 votes vote down vote up
/**
 *
 */
private void testIfSlide( int index ){
    if ( index <= 0 ) throw new IllegalArgumentException("Bad parameter for index");
    try {
        UiObject title = mDevice.findObject(
                new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/title")
        );
        UiObject description = mDevice.findObject(
                new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/description")
        );
        UiObject next = mDevice.findObject(
                new UiSelector().resourceId(PACKAGE_APP_PATH + ":id/skip")
        );
        assertEquals(sTitles[index - 1], title.getText());
        assertEquals(sSummaries[index-1], description.getText());
        assertTrue(next.exists());
    } catch ( UiObjectNotFoundException uonfe ){
        uonfe.printStackTrace();
        fail(uonfe.getMessage() );
    }
}
 
Example #7
Source File: ItStandaloneModeDialog.java    From SmoothClicker with MIT License 6 votes vote down vote up
/**
 * Opens the standalone mode dialog
 */
private void openStandaloneModeDialog(){
    try {
        // Display the pop-up
        UiObject menu = mDevice.findObject(
                new UiSelector().className("android.widget.ImageView")
                        //.description("Plus d'options") // FIXME Raw french string
                        .description("Autres options") // WARNING FIXME French string used, use instead system R values
        );
        menu.click();
        UiObject menuItem = mDevice.findObject(
                new UiSelector().className("android.widget.TextView").text(InstrumentationRegistry.getTargetContext().getString(R.string.action_standalone))
        );
        menuItem.click();
    } catch ( UiObjectNotFoundException uinfe ){
        uinfe.printStackTrace();
        fail(uinfe.getMessage());
    }
}
 
Example #8
Source File: UiWatchers.java    From AppCrawler with Apache License 2.0 6 votes vote down vote up
public boolean handleAnr2() {
    UiObject window = sDevice.findObject(new UiSelector().packageName("android")
            .textContains("isn't responding."));
    if (!window.exists()) {
        window = sDevice.findObject(new UiSelector().packageName("android")
                .textContains("沒有回應"));
    }
    if (window.exists()) {
        String errorText = null;
        try {
            errorText = window.getText();
        } catch (UiObjectNotFoundException e) {
            Log.e(TAG, "dialog gone?", e);
        }
        onAnrDetected(errorText);
        postHandler();
        return true; // triggered
    }
    return false; // no trigger
}
 
Example #9
Source File: UiWatchers.java    From AppCrawler with Apache License 2.0 6 votes vote down vote up
public boolean handleCrash2() {
    UiObject window = sDevice.findObject(new UiSelector().packageName("android")
            .textContains("has stopped"));
    if (!window.exists()) {
        window = sDevice.findObject(new UiSelector().packageName("android")
                .textContains("已停止運作"));
    }
    if (window.exists()) {
        String errorText = null;
        try {
            errorText = window.getText();
        } catch (UiObjectNotFoundException e) {
            Log.e(TAG, "dialog gone?", e);
        }
        UiHelper.takeScreenshots("[CRASH]");
        onCrashDetected(errorText);
        postHandler();
        return true; // triggered
    }
    return false; // no trigger
}
 
Example #10
Source File: UiHelper.java    From AppCrawler with Apache License 2.0 6 votes vote down vote up
public static boolean handleCommonDialog() {
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    UiObject button = null;
    for (String keyword : Config.COMMON_BUTTONS) {
        button = device.findObject(new UiSelector().text(keyword).enabled(true));
        if (button != null && button.exists()) {
            break;
        }
    }
    try {
        // sometimes it takes a while for the OK button to become enabled
        if (button != null && button.exists()) {
            button.waitForExists(5000);
            button.click();
            Log.i("AppCrawlerAction", "{Click} " + button.getText() + " Button succeeded");
            return true; // triggered
        }
    } catch (UiObjectNotFoundException e) {
        Log.w(TAG, "UiObject disappear");
    }
    return false; // no trigger
}
 
Example #11
Source File: UiHelper.java    From AppCrawler with Apache License 2.0 6 votes vote down vote up
public static void inputRandomTextToEditText() {
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    UiObject edit = null;
    int i = 0;
    do {
        edit = null;
        edit = device.findObject(new UiSelector().className("android.widget.EditText").instance(i++));
        if (edit != null && edit.exists()) {
            try {
                Random rand = new Random();
                String text = Config.RANDOM_TEXT[rand.nextInt(Config.RANDOM_TEXT.length - 1)];
                edit.setText(text);
            } catch (UiObjectNotFoundException e) {
                // Don't worry
            }
        }
    } while (edit != null && edit.exists());
}
 
Example #12
Source File: UIUtil.java    From SweetBlue with GNU General Public License v3.0 6 votes vote down vote up
public static boolean viewExistsContains(UiDevice device, String... textToMatch) throws UiObjectNotFoundException
{
    if (textToMatch == null || textToMatch.length < 1)
    {
        return false;
    }
    UiObject view;
    boolean contains = false;
    for (int i = 0; i < textToMatch.length; i++)
    {
        view = device.findObject(new UiSelector().textContains(textToMatch[i]));
        contains = view.exists();
        if (contains) return true;
    }
    return false;
}
 
Example #13
Source File: ObjInfo.java    From android-uiautomator-server with MIT License 6 votes vote down vote up
private ObjInfo(UiObject obj) throws UiObjectNotFoundException {
	this._bounds = Rect.from(obj.getBounds());
	this._checkable = obj.isCheckable();
	this._checked = obj.isChecked();
	this._childCount = obj.getChildCount();
	this._clickable = obj.isClickable();
	this._contentDescription = obj.getContentDescription();
	this._enabled = obj.isEnabled();
	this._focusable = obj.isFocusable();
	this._focused = obj.isFocused();
	this._longClickable = obj.isLongClickable();
	this._packageName = obj.getPackageName();
	this._scrollable = obj.isScrollable();
	this._selected = obj.isSelected();
	this._text = obj.getText();
       this._visibleBounds = Rect.from(obj.getVisibleBounds());
       this._className = obj.getClassName();
}
 
Example #14
Source File: BasicUITests.java    From restcomm-android-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
private void allowPermissionsIfNeeded() {
    if (Build.VERSION.SDK_INT >= 23) {
        // Initialize UiDevice instance
        UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

        // notice that we typically receive 2-3 permission prompts, hence the loop
        while (true) {
            UiObject allowPermissions = uiDevice.findObject(new UiSelector().text("Allow"));
            if (allowPermissions.exists()) {
                try {
                    allowPermissions.click();
                } catch (UiObjectNotFoundException e) {
                    e.printStackTrace();
                    Log.e(TAG, "There is no permissions dialog to interact with ");
                }
            } else {
                break;
            }
        }
    }
}
 
Example #15
Source File: LoginActivityTest.java    From twittererer with Apache License 2.0 5 votes vote down vote up
@Test
public void loginCancelled() throws UiObjectNotFoundException {
    UiObject loginButton = device.findObject(new UiSelector().text(LOGIN_BUTTON_TEXT));
    loginButton.clickAndWaitForNewWindow(TIMEOUT);

    // TODO: this fails to find the text on API 24+ (Android 7+) for some reason
    UiObject allowButton = device.findObject(new UiSelector().text("Cancel"));
    allowButton.clickAndWaitForNewWindow(TIMEOUT);

    loginButton = device.findObject(new UiSelector().text(LOGIN_BUTTON_TEXT));
    assertThat(loginButton, notNullValue());
}
 
Example #16
Source File: AutomatorServiceImpl.java    From android-uiautomator-server with MIT License 5 votes vote down vote up
private UiObject getUiObject(String name) throws UiObjectNotFoundException {
    if (uiObjects.containsKey(name)) {
        return uiObjects.get(name);
    } else {
        throw new UiObjectNotFoundException("UiObject " + name + " not found!");
    }
}
 
Example #17
Source File: ComprehensionTest.java    From BuildmLearn-Toolkit-Android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void allowPermissionsIfNeeded() {
    if (Build.VERSION.SDK_INT >= 23) {
        UiDevice device = UiDevice.getInstance(getInstrumentation());
        UiObject allowPermissions = device.findObject(new UiSelector().text("Allow"));
        if (allowPermissions.exists()) {
            try {
                allowPermissions.click();
            } catch (UiObjectNotFoundException e) {
            }
        }
    }
}
 
Example #18
Source File: SignInActivityTest.java    From ribot-app-android with Apache License 2.0 5 votes vote down vote up
private void allowPermissionsIfNeeded()  {
    if (Build.VERSION.SDK_INT >= 23) {
        UiObject allowPermissions = mDevice.findObject(new UiSelector().text("Allow"));
        if (allowPermissions.exists()) {
            try {
                allowPermissions.click();
            } catch (UiObjectNotFoundException e) {
                Timber.w(e, "There is no permissions dialog to interact with ");
            }
        }
    }
}
 
Example #19
Source File: LoginActivityTest.java    From twittererer with Apache License 2.0 5 votes vote down vote up
@Test
public void loginSuccessful() throws UiObjectNotFoundException {
    UiObject loginButton = device.findObject(new UiSelector().text(LOGIN_BUTTON_TEXT));
    loginButton.clickAndWaitForNewWindow(TIMEOUT);

    // TODO: this fails to find the text on API 24+ (Android 7+) for some reason
    UiObject allowButton = device.findObject(new UiSelector().text("Allow"));
    allowButton.clickAndWaitForNewWindow(TIMEOUT);

    UiObject activityTitle = device.findObject(new UiSelector()
            .text(getInstrumentation().getTargetContext().getString(R.string.title_activity_twitter_feed)));
    assertThat(activityTitle, notNullValue());
}
 
Example #20
Source File: AutomatorServiceImpl.java    From android-uiautomator-server with MIT License 5 votes vote down vote up
private boolean longClick(UiObject obj, String corner) throws UiObjectNotFoundException {
    if (corner == null) corner = "center";

    corner = corner.toLowerCase();
    if ("br".equals(corner) || "bottomright".equals(corner)) return obj.longClickBottomRight();
    else if ("tl".equals(corner) || "topleft".equals(corner)) return obj.longClickTopLeft();
    else if ("c".equals(corner) || "center".equals(corner)) return obj.longClick();

    return false;
}
 
Example #21
Source File: AutomatorServiceImpl.java    From android-uiautomator-server with MIT License 5 votes vote down vote up
private boolean click(UiObject obj, String corner) throws UiObjectNotFoundException {
    if (corner == null) corner = "center";
    corner = corner.toLowerCase();
    if ("br".equals(corner) || "bottomright".equals(corner)) return obj.clickBottomRight();
    else if ("tl".equals(corner) || "topleft".equals(corner)) return obj.clickTopLeft();
    else if ("c".equals(corner) || "center".equals(corner)) return obj.click();
    return false;
}
 
Example #22
Source File: SelectorWatcher.java    From android-uiautomator-server with MIT License 5 votes vote down vote up
@Override
public boolean checkForCondition() {
    for (UiSelector s : conditions) {
        UiObject obj = new UiObject(s);
        if (!obj.exists()) return false;
    }
    action();
    return true;
}
 
Example #23
Source File: UiAutomatorUtils.java    From Forage with Mozilla Public License 2.0 5 votes vote down vote up
public static void allowPermissionsIfNeeded(UiDevice device) {
    if (Build.VERSION.SDK_INT >= 23) {
        UiObject allowPermissions = device.findObject(new UiSelector().text(TEXT_ALLOW));

        if (allowPermissions.exists()) {
            try {
                allowPermissions.click();
            } catch (UiObjectNotFoundException ignored) {
            }
        }
    }
}
 
Example #24
Source File: MainEspressoTest.java    From AndroidProjects with MIT License 5 votes vote down vote up
@Test
public void d() throws UiObjectNotFoundException {
    // Initialize UiDevice instance
    mDevice = UiDevice.getInstance(getInstrumentation());

    // Perform a short press on the HOME button
    mDevice.pressHome();

    // Bring up the default launcher by searching for
    // a UI component that matches the content-description for the launcher button
    UiObject allAppsButton = mDevice.findObject(new UiSelector().description("Apps"));

    // Perform a click on the button to bring up the launcher
    allAppsButton.clickAndWaitForNewWindow();
}
 
Example #25
Source File: UiScreen.java    From AppCrawler with Apache License 2.0 5 votes vote down vote up
private boolean parseSignature(UiObject uiObject) {
    //Log.v(TAG, new Exception().getStackTrace()[0].getMethodName() + "()");
    if ((uiObject == null) || !uiObject.exists())
        return false;

    if (signature.length() > Config.sScreenSignatueLength)
        return true;

    try {
        // Screen signature: use classname list in the view hierarchy
        String classname = "";
        for (String tmp : uiObject.getClassName().split("\\.")) {
            classname = tmp;
        }
        signature = signature.concat(classname + ";");

        // Add all children recursively
        for (int i = 0; i < uiObject.getChildCount(); i++) {
            parseSignature(uiObject.getChild(new UiSelector().index(i)));
        }
    } catch (UiObjectNotFoundException e) {
        Log.e(TAG, "uiObject does not exists during parsing");
        return false;
    }

    return true;
}
 
Example #26
Source File: UIUtil.java    From SweetBlue with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Clicks a button with the given text. This will try to find the widget exactly as the text is given, and
 * will try upper casing the text if it is not found.
 */
public static void clickButton(UiDevice device, String buttonText) throws UiObjectNotFoundException
{
    UiObject accept = device.findObject(new UiSelector().text(buttonText));
    if (accept.exists())
    {
        accept.click();
        return;
    }
    accept = device.findObject(new UiSelector().text(buttonText.toUpperCase()));
    accept.click();
}
 
Example #27
Source File: ItNotificationsManager.java    From SmoothClicker with MIT License 5 votes vote down vote up
/**
 * Inner method to get a dedicated notification and test if this notification is clicakble and display the good activity on click
 * @param textContent - The text to use to get the notification
 */
private void testNotificationClick( String textContent ){

    UiObject n = null;

    if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH ){
        n = mDevice.findObject(
                new UiSelector()
                        .resourceId("android:id/text")
                        .className("android.widget.TextView")
                        .packageName("pylapp.smoothclicker.android")
                        .textContains(textContent));
    } else {
        n = mDevice.findObject(
                new UiSelector()
                        .resourceId("android:id/text")
                        .className("android.widget.TextView")
                        .packageName("com.android.systemui")
                        .textContains(textContent));
    }

    mDevice.openNotification();
    n.waitForExists(2000);

    try {
        n.click();
        w(5000);
        assertEquals(ClickerActivity.class.getSimpleName(), getActivityInstance().getClass().getSimpleName());
    } catch ( UiObjectNotFoundException uonfe ){
        uonfe.printStackTrace();
        fail();
    }

}
 
Example #28
Source File: EspSystemDialog.java    From espresso-macchiato with MIT License 5 votes vote down vote up
protected void click(String target) {
    UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    UiObject button = device.findObject(new UiSelector().text(target));

    try {
        button.click();
    } catch (UiObjectNotFoundException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #29
Source File: ItStatusBarNotifier.java    From SmoothClicker with MIT License 5 votes vote down vote up
/**
 * Inner method to get a dedicated notification and test it
 * @param textContent - The text to use to get the notification
 */
private void testNotification( String textContent ){

    if ( textContent == null ) textContent = "";

    UiObject n = null;

    if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH ){
        n = mDevice.findObject(
                new UiSelector()
                        .resourceId("android:id/text")
                        .className("android.widget.TextView")
                        .packageName("pylapp.smoothclicker.android")
                        .textContains(textContent));
    } else {
        n = mDevice.findObject(
                new UiSelector()
                        .resourceId("android:id/text")
                        .className("android.widget.TextView")
                        .packageName("com.android.systemui")
                        .textContains(textContent));
    }

    mDevice.openNotification();
    n.waitForExists(2000);
    assertTrue(n.exists());

}
 
Example #30
Source File: AutomatorServiceImpl.java    From android-uiautomator-server with MIT License 5 votes vote down vote up
/**
 * Searches for child UI element within the constraints of this UiSelector selector. It looks for any child matching the childPattern argument that has a child UI element anywhere within its sub hierarchy that has a text attribute equal to text. The returned UiObject will point at the childPattern instance that matched the search and not at the identifying child element that matched the text attribute.
 *
 * @param collection Selector of UiCollection or UiScrollable.
 * @param text       String of the identifying child contents of of the childPattern
 * @param child      UiSelector selector of the child pattern to match and return
 * @return A string ID represent the returned UiObject.
 */
@Override
public String childByText(Selector collection, Selector child, String text) throws UiObjectNotFoundException {
    UiObject obj;
    if (exist(collection) && objInfo(collection).isScrollable()) {
        obj = new UiScrollable(collection.toUiSelector()).getChildByText(child.toUiSelector(), text);
    } else {
        obj = new UiCollection(collection.toUiSelector()).getChildByText(child.toUiSelector(), text);
    }
    return addUiObject(obj);
}