androidx.test.uiautomator.UiObject Java Examples

The following examples show how to use androidx.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: UiObject2Element.java    From appium-uiautomator2-server with Apache License 2.0 6 votes vote down vote up
@Override
public List<?> getChildren(final Object selector, final By by) throws UiObjectNotFoundException {
    if (selector instanceof UiSelector) {
        /*
         * We can't find the child elements with UiSelector on UiObject2,
         * as an alternative creating UiObject with UiObject2's AccessibilityNodeInfo
         * and finding the child elements on UiObject.
         */
        AccessibilityNodeInfo nodeInfo = AccessibilityNodeInfoGetter.fromUiObject(element);

        UiSelector uiSelector = new UiSelector();
        CustomUiSelector customUiSelector = new CustomUiSelector(uiSelector);
        uiSelector = customUiSelector.getUiSelector(nodeInfo);
        UiObject uiObject = (UiObject) CustomUiDevice.getInstance().findObject(uiSelector);
        String id = UUID.randomUUID().toString();
        AndroidElement androidElement = getAndroidElement(id, uiObject, true, by, getContextId());
        return androidElement.getChildren(selector, by);
    }
    return element.findObjects((BySelector) selector);
}
 
Example #2
Source File: AutomatorAssertion.java    From device-automator with MIT License 6 votes vote down vote up
/**
 * Asserts that the ui element specified in {@link DeviceAutomator#onDevice(UiObjectMatcher)}
 * has a content description that matches the given matcher.
 *
 * @param matcher The <a href="http://hamcrest.org/JavaHamcrest/">Hamcrest</a> to match against.
 * @return
 */
public static AutomatorAssertion contentDescription(final Matcher matcher) {
    return new AutomatorAssertion() {
        @Override
        public void wrappedCheck(UiObject object) throws UiObjectNotFoundException {
            visible(true).check(object);
            if (!matcher.matches(object.getContentDescription())) {
                StringDescription description = new StringDescription();
                description.appendText("Expected ");
                matcher.describeTo(description);
                description.appendText(" ");
                matcher.describeMismatch(object.getText(), description);
                assertTrue(description.toString(), false);
            }
        }
    };
}
 
Example #3
Source File: BrowserScreenScreenshots.java    From focus-android with Mozilla Public License 2.0 6 votes vote down vote up
private void takeScreenshotOfFindDialog() throws Exception {
    UiObject findinpageMenuItem = device.findObject(new UiSelector()
            .resourceId(TestHelper.getAppName() + ":id/find_in_page")
            .enabled(true));
    UiObject findinpageCloseBtn = device.findObject(new UiSelector()
            .resourceId(TestHelper.getAppName() + ":id/close_find_in_page")
            .enabled(true));

    TestHelper.menuButton.perform(click());
    findinpageMenuItem.waitForExists(waitingTime);
    findinpageMenuItem.click();

    findinpageCloseBtn.waitForExists(waitingTime);
    Screengrab.screenshot("Find_In_Page_Dialog");
    findinpageCloseBtn.click();
}
 
Example #4
Source File: AutomatorAssertion.java    From device-automator with MIT License 6 votes vote down vote up
/**
 * Asserts that the ui element specified in {@link DeviceAutomator#onDevice(UiObjectMatcher)}
 * has text that matches the given matcher.
 *
 * @param matcher The <a href="http://hamcrest.org/JavaHamcrest/">Hamcrest</a> to match against.
 * @return
 */
public static AutomatorAssertion text(final Matcher matcher) {
    return new AutomatorAssertion() {
        @Override
        public void wrappedCheck(UiObject object) throws UiObjectNotFoundException {
            visible(true).check(object);
            if (!matcher.matches(object.getText())) {
                StringDescription description = new StringDescription();
                description.appendText("Expected ");
                matcher.describeTo(description);
                description.appendText(" ");
                matcher.describeMismatch(object.getText(), description);
                assertTrue(description.toString(), false);
            }
        }
    };
}
 
Example #5
Source File: TestAddNumber.java    From quickstart-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddNumber() {
  ViewInteraction firstNumber = onView(withId(R.id.fieldFirstNumber));
  ViewInteraction secondNumber = onView(withId(R.id.fieldSecondNumber));
  ViewInteraction addButton = onView(withId(R.id.buttonCalculate));

  firstNumber.perform(replaceText("32"));
  secondNumber.perform(replaceText("16"));

  addButton.perform(scrollTo(), click());

  Assert.assertTrue(
      new UiObject(new UiSelector()
        .resourceId("com.google.samples.quickstart.functions:id/fieldAddResult").text("48"))
      .waitForExists(60000));
}
 
Example #6
Source File: UiObjectChildGenerator.java    From appium-uiautomator2-server with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public Object next() {
    if (curChild == -1) {
        init();
    }

    Object child;
    if (parent instanceof UiObject) {
        try {
            child = ((UiObject) parent).getChild(new UiSelector().index(curChild));
        } catch (UiObjectNotFoundException e) {
            child = null;
        }
    } else {
        child = uiObject2Children.get(curChild);
    }
    ++curChild;
    return child;
}
 
Example #7
Source File: AutomatorActionTest.java    From device-automator with MIT License 6 votes vote down vote up
@Test(timeout = 1000)
public void perform() throws InterruptedException {
    final UiSelector expectedSelector = mock(UiSelector.class);
    final UiObject expectedObject = mock(UiObject.class);
    final CountDownLatch latch = new CountDownLatch(1);
    AutomatorAction action = new AutomatorAction() {
        @Override
        public void wrappedPerform(UiSelector selector, UiObject object) throws UiObjectNotFoundException {
            assertEquals(expectedSelector, selector);
            assertEquals(expectedObject, object);
            latch.countDown();
        }
    };

    action.perform(expectedSelector, expectedObject);

    latch.await();
}
 
Example #8
Source File: ScrollToElement.java    From appium-uiautomator2-server with Apache License 2.0 6 votes vote down vote up
@Override
public boolean scrollIntoView(UiObject obj) throws UiObjectNotFoundException {
    if (obj.exists()) {
        return true;
    }

    // we will need to reset the search from the beginning to start search
    flingToBeginning(getMaxSearchSwipes());
    if (obj.exists()) {
        return true;
    }

    for (int x = 0; x < getMaxSearchSwipes(); x++) {
        if (!scrollForward()) {
            return false;
        }

        if (obj.exists()) {
            return true;
        }
    }

    return false;
}
 
Example #9
Source File: BrowserSignInTest.java    From samples-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testA_cancelSignIn() throws UiObjectNotFoundException {
    getProgressBar().waitUntilGone(NETWORK_TIMEOUT);
    onView(withId(R.id.clear_data_btn)).check(matches(isDisplayed()));
    onView(withId(R.id.clear_data_btn)).perform(click());
    onView(withId(R.id.browser_sign_in_btn)).check(matches(isDisplayed()));

    onView(withId(R.id.browser_sign_in_btn)).perform(click());
    mDevice.wait(Until.findObject(By.pkg(CHROME_STABLE)), TRANSITION_TIMEOUT);

    UiSelector selector = new UiSelector();
    UiObject closeBrowser = mDevice.findObject(selector.resourceId(ID_CLOSE_BROWSER));
    closeBrowser.click();

    mDevice.wait(Until.findObject(By.pkg(SAMPLE_APP)), TRANSITION_TIMEOUT);
    onView(withText(R.string.auth_canceled)).inRoot(new ToastMatcher()).check(matches(isDisplayed()));
}
 
Example #10
Source File: UiObject2Element.java    From appium-uiautomator2-server with Apache License 2.0 6 votes vote down vote up
@Override
public boolean dragTo(Object destObj, int steps) throws UiObjectNotFoundException {
    if (destObj instanceof UiObject) {
        int destX = ((UiObject) destObj).getBounds().centerX();
        int destY = ((UiObject) destObj).getBounds().centerY();
        element.drag(new android.graphics.Point(destX, destY), steps);
        return true;
    }
    if (destObj instanceof UiObject2) {
        android.graphics.Point coord = ((UiObject2) destObj).getVisibleCenter();
        element.drag(coord, steps);
        return true;
    }
    Logger.error("Destination should be either UiObject or UiObject2");
    return false;
}
 
Example #11
Source File: BrowserSignInTest.java    From samples-android with Apache License 2.0 6 votes vote down vote up
private void customTabInteraction(boolean enterUserName) throws UiObjectNotFoundException {
    mDevice.wait(Until.findObject(By.pkg(CHROME_STABLE)), TRANSITION_TIMEOUT);
    acceptChromePrivacyOption();
    UiSelector selector = new UiSelector();
    if (enterUserName) {
        UiObject username = mDevice.findObject(selector.resourceId(ID_USERNAME));
        username.setText(USERNAME);
    }
    UiObject password = mDevice.findObject(selector.resourceId(ID_PASSWORD));
    password.setText(PASSWORD);
    UiObject signIn = mDevice.findObject(selector.resourceId(ID_SUBMIT));
    signIn.click();
    mDevice.wait(Until.findObject(By.pkg(SAMPLE_APP)), TRANSITION_TIMEOUT);
    //wait for token exchange
    getProgressBar().waitUntilGone(NETWORK_TIMEOUT);
}
 
Example #12
Source File: ElementHelpers.java    From appium-uiautomator2-server with Apache License 2.0 6 votes vote down vote up
/**
 * Remove all duplicate elements from the provided list
 *
 * @param elements - elements to remove duplicates from
 * @return a new list with duplicates removed
 */
public static List<Object> dedupe(List<Object> elements) {
    try {
        findAccessibilityNodeInfo = method(UiObject.class, "findAccessibilityNodeInfo", long.class);
    } catch (Exception e) {
        e.printStackTrace();
    }

    List<Object> result = new ArrayList<>();
    List<AccessibilityNodeInfo> nodes = new ArrayList<>();

    for (Object element : elements) {
        AccessibilityNodeInfo node = elementToNode(element);
        if (!nodes.contains(node)) {
            nodes.add(node);
            result.add(element);
        }
    }

    return result;
}
 
Example #13
Source File: AutomatorActionTest.java    From device-automator with MIT License 6 votes vote down vote up
@Test
public void check_doesNotClickObjectIfObjectNotCheckable() throws UiObjectNotFoundException {
    UiObject uncheckedObject = mock(UiObject.class);
    when(uncheckedObject.isCheckable()).thenReturn(false);
    when(uncheckedObject.isChecked()).thenReturn(false);

    AutomatorAction.check(true).perform(null, uncheckedObject);

    verify(uncheckedObject, times(0)).click();

    UiObject checkedObject = mock(UiObject.class);
    when(checkedObject.isCheckable()).thenReturn(false);
    when(checkedObject.isChecked()).thenReturn(true);

    AutomatorAction.check(false).perform(null, checkedObject);

    verify(checkedObject, times(0)).click();
}
 
Example #14
Source File: UiObject2Element.java    From appium-uiautomator2-server with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public Object getChild(final Object selector) throws UiObjectNotFoundException {
    if (selector instanceof UiSelector) {
        /*
         * We can't find the child element with UiSelector on UiObject2,
         * as an alternative creating UiObject with UiObject2's AccessibilityNodeInfo
         * and finding the child element on UiObject.
         */
        AccessibilityNodeInfo nodeInfo = AccessibilityNodeInfoGetter.fromUiObject(element);

        UiSelector uiSelector = new UiSelector();
        CustomUiSelector customUiSelector = new CustomUiSelector(uiSelector);
        uiSelector = customUiSelector.getUiSelector(nodeInfo);
        Object uiObject = CustomUiDevice.getInstance().findObject(uiSelector);
        if (uiObject instanceof UiObject) {
            AccessibilityNodeInfoGetter.fromUiObject(element);
            return ((UiObject) uiObject).getChild((UiSelector) selector);
        }
        return null;
    }
    return element.findObject((BySelector) selector);
}
 
Example #15
Source File: AutomatorActionTest.java    From device-automator with MIT License 5 votes vote down vote up
@Test
public void swipeLeft() throws UiObjectNotFoundException {
    UiObject object = mock(UiObject.class);

    AutomatorAction.swipeLeft(5).perform(null, object);

    verify(object).swipeLeft(5);
}
 
Example #16
Source File: DeviceAutomatorTest.java    From device-automator with MIT License 5 votes vote down vote up
@Test
public void isChecked_returnsTrueIfObjectIsChecked() throws UiObjectNotFoundException {
    UiObject object = mock(UiObject.class);
    when(object.isChecked()).thenReturn(true);
    UiObjectMatcher matcher = mock(UiObjectMatcher.class);
    when(matcher.getUiObject(mUiDevice)).thenReturn(object);
    DeviceAutomator deviceAutomator = getDeviceAutomator(matcher);

    assertTrue(deviceAutomator.isChecked());
}
 
Example #17
Source File: AutomatorAssertionTest.java    From device-automator with MIT License 5 votes vote down vote up
@Test
public void visible_true_assertionFailsWhenObjectHasNoHeight() throws UiObjectNotFoundException {
    Rect rect = mock(Rect.class);
    when(rect.height()).thenReturn(0);
    when(rect.width()).thenReturn(1);
    UiObject object = mock(UiObject.class);
    when(object.getVisibleBounds()).thenReturn(rect);

    try {
        AutomatorAssertion.visible(true).check(object);
    } catch (AssertionFailedError e) {
        assertEquals("Matched view was not visible", e.getMessage());
    }
}
 
Example #18
Source File: DeviceAutomatorTest.java    From device-automator with MIT License 5 votes vote down vote up
@Test
public void isChecked_returnsFalseIfObjectIsNotChecked() throws UiObjectNotFoundException {
    UiObject object = mock(UiObject.class);
    when(object.isChecked()).thenReturn(false);
    UiObjectMatcher matcher = mock(UiObjectMatcher.class);
    when(matcher.getUiObject(mUiDevice)).thenReturn(object);
    DeviceAutomator deviceAutomator = getDeviceAutomator(matcher);

    assertFalse(deviceAutomator.isChecked());
}
 
Example #19
Source File: AutomatorAssertionTest.java    From device-automator with MIT License 5 votes vote down vote up
@Test
public void visible_true_assertionFailsWhenObjectReturnsNullVisibleBounds() {
    try {
        AutomatorAssertion.visible(true).check(mock(UiObject.class));
    } catch (AssertionFailedError e) {
        assertEquals("Matched view did not have any visible bounds", e.getMessage());
    }
}
 
Example #20
Source File: AutomatorAssertionTest.java    From device-automator with MIT License 5 votes vote down vote up
@Test
public void visible_false_assertionFailsWhenObjectHasAHeight() throws UiObjectNotFoundException {
    Rect rect = mock(Rect.class);
    when(rect.height()).thenReturn(1);
    when(rect.width()).thenReturn(0);
    UiObject object = mock(UiObject.class);
    when(object.getVisibleBounds()).thenReturn(rect);

    try {
        AutomatorAssertion.visible(false).check(object);
    } catch (AssertionFailedError e) {
        assertEquals("Matched view was visible", e.getMessage());
    }
}
 
Example #21
Source File: AutomatorAssertionTest.java    From device-automator with MIT License 5 votes vote down vote up
@Test
public void visible_true_isSuccessfulWhenViewHasHeightAndWidth() throws UiObjectNotFoundException {
    Rect rect = mock(Rect.class);
    when(rect.height()).thenReturn(1);
    when(rect.width()).thenReturn(1);
    UiObject object = mock(UiObject.class);
    when(object.getVisibleBounds()).thenReturn(rect);

    AutomatorAssertion.visible(true).check(object);
}
 
Example #22
Source File: AutomatorAction.java    From device-automator with MIT License 5 votes vote down vote up
/**
 * Performs the swipe left action on the UiObject. The swipe gesture can be performed over any surface.
 * The targeted UI element does not need to be scrollable.
 *
 * @param steps indicates the number of injected move steps into the system. Steps are injected about 5ms apart.
 *              So a 100 steps may take about 1/2 second to complete.
 * @return
 */
public static AutomatorAction swipeLeft(final int steps) {
    return new AutomatorAction() {
        @Override
        public void wrappedPerform(UiSelector selector, UiObject object) throws UiObjectNotFoundException {
            object.swipeLeft(steps);
        }
    };
}
 
Example #23
Source File: AutomatorAction.java    From device-automator with MIT License 5 votes vote down vote up
/**
 * Performs a click on the ui element specified in
 * {@link DeviceAutomator#onDevice(UiObjectMatcher)}.
 *
 * @return
 */
public static AutomatorAction click() {
    return new AutomatorAction() {
        @Override
        public void wrappedPerform(UiSelector selector, UiObject object) throws UiObjectNotFoundException {
            object.click();
        }
    };
}
 
Example #24
Source File: AutomatorActionTest.java    From device-automator with MIT License 5 votes vote down vote up
@Test
public void click() throws UiObjectNotFoundException {
    UiObject object = mock(UiObject.class);

    AutomatorAction.click().perform(null, object);

    verify(object).click();
}
 
Example #25
Source File: UiScrollableParserTests.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
@Override
protected UiScrollable consumeConstructor() throws UiSelectorSyntaxException,
        UiObjectNotFoundException {
    UiScrollable self = super.consumeConstructor();
    uiScrollableSpy = spy(getTarget());
    doReturn(true).when(uiScrollableSpy).scrollIntoView(any(UiSelector.class));
    doReturn(true).when(uiScrollableSpy).scrollIntoView(any(UiObject.class));
    doReturn(uiObject).when(uiScrollableSpy).getChildByText(any(UiSelector.class),
            anyString(), anyBoolean());
    doThrow(new UiObjectNotFoundException("not found")).when(uiScrollableSpy)
            .getChildByText(any(UiSelector.class), anyString());
    doReturn(true).when(uiScrollableSpy).scrollForward(anyInt());
    setTarget(uiScrollableSpy);
    return self;
}
 
Example #26
Source File: AccessibilityNodeInfoGetter.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
@Nullable
public static AccessibilityNodeInfo fromUiObjectDefaultTimeout(Object object) {
    long timeout = TIME_IN_MS;
    if (object instanceof UiObject) {
        timeout = (long) ReflectionUtils.getField(UiObject.class,
                "WAIT_FOR_SELECTOR_TIMEOUT", object);
    }
    return fromUiObject(object, timeout);
}
 
Example #27
Source File: AccessibilityNodeInfoGetter.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
@Nullable
public static AccessibilityNodeInfo fromUiObject(Object object, long timeout) {
    if (object instanceof UiObject2) {
        return (AccessibilityNodeInfo) invoke(method(UiObject2.class,
                "getAccessibilityNodeInfo"), object);
    } else if (object instanceof UiObject) {
        return (AccessibilityNodeInfo) invoke(method(UiObject.class,
                "findAccessibilityNodeInfo", long.class), object, timeout);
    }
    throw new UiAutomator2Exception("Unknown object type: " + object.getClass().getName());
}
 
Example #28
Source File: UiObjectChildGenerator.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
private void init() {
    if (parent instanceof UiObject) {
        try {
            childCount = ((UiObject) parent).getChildCount();
        } catch (UiObjectNotFoundException e) {
            Logger.error("Could not get child count from UiObject");
            childCount = 0;
        }
    } else {
        uiObject2Children = ((UiObject2) parent).getChildren();
        childCount = uiObject2Children.size();
    }
    curChild = 0;
}
 
Example #29
Source File: UiObjectElement.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
@Override
public boolean dragTo(final Object destObj, final int steps) throws UiObjectNotFoundException {
    if (destObj instanceof UiObject) {
        return element.dragTo((UiObject) destObj, steps);
    }

    if (destObj instanceof UiObject2) {
        android.graphics.Point coords = ((UiObject2) destObj).getVisibleCenter();
        return dragTo(coords.x, coords.y, steps);
    }

    Logger.error("Destination should be either UiObject or UiObject2");
    return false;
}
 
Example #30
Source File: UiObjectElement.java    From appium-uiautomator2-server with Apache License 2.0 5 votes vote down vote up
public UiObjectElement(String id, UiObject element, boolean isSingleMatch, By by,
                       @Nullable String contextId) {
    this.id = id;
    this.element = element;
    this.by = by;
    this.contextId = contextId;
    this.isSingleMatch = isSingleMatch;
}