androidx.test.espresso.NoMatchingViewException Java Examples

The following examples show how to use androidx.test.espresso.NoMatchingViewException. 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: AuthenticatorActivityTest.java    From google-authenticator-android with Apache License 2.0 6 votes vote down vote up
@TargetApi(11)
private static void openListViewContextualActionBarAndInvokeItem(
    AuthenticatorActivity activity,
    final ListView listView,
    final int position,
    final int menuItemId) {
  ActionMode actionMode =
      (ActionMode) openListViewContextualActionBar(activity, listView, position);
  MenuItem menuItem = actionMode.getMenu().findItem(menuItemId);
  try {
    onView(withContentDescription(menuItem.getTitle().toString())).perform(click());
  } catch (NoMatchingViewException e) {
    // Might be in the overflow menu
    Espresso.openActionBarOverflowOrOptionsMenu(activity);
    onView(withText(menuItem.getTitle().toString())).perform(click());
  }
}
 
Example #2
Source File: ViewAssertionsTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  mTargetContext = getApplicationContext();
  presentView = new View(mTargetContext);
  absentView = null;
  absentException = null;
  alwaysAccepts = is(presentView);
  alwaysFails = not(is(presentView));
  nullViewMatcher = nullValue(View.class);

  presentException =
      new NoMatchingViewException.Builder()
          .withViewMatcher(alwaysFails)
          .withRootView(new View(mTargetContext))
          .build();
}
 
Example #3
Source File: ViewAssertions.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Override
public void check(View view, NoMatchingViewException noViewException) {
  StringDescription description = new StringDescription();
  description.appendText("'");
  viewMatcher.describeTo(description);
  if (noViewException != null) {
    description.appendText(
        String.format(
            Locale.ROOT,
            "' check could not be performed because view '%s' was not found.\n",
            noViewException.getViewMatcherDescription()));
    Log.e(TAG, description.toString());
    throw noViewException;
  } else {
    description.appendText("' doesn't match the selected view.");
    assertThat(description.toString(), view, viewMatcher);
  }
}
 
Example #4
Source File: AccessibilityChecks.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
  if (noViewFoundException != null) {
    Log.e(
        TAG,
        String.format(
            "'accessibility checks could not be performed because view '%s' was not"
                + "found.\n",
            noViewFoundException.getViewMatcherDescription()));
    throw noViewFoundException;
  }
  if (view == null) {
    throw new NullPointerException();
  }
  StrictMode.ThreadPolicy originalPolicy = StrictMode.allowThreadDiskWrites();
  try {
    CHECK_EXECUTOR.checkAndReturnResults(view);
  } finally {
    StrictMode.setThreadPolicy(originalPolicy);
  }
}
 
Example #5
Source File: AccessibilityChecks.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
  if (noViewFoundException != null) {
    Log.e(
        TAG,
        String.format(
            "'accessibility checks could not be performed because view '%s' was not"
                + "found.\n",
            noViewFoundException.getViewMatcherDescription()));
    throw noViewFoundException;
  }
  if (view == null) {
    throw new NullPointerException();
  }
  StrictMode.ThreadPolicy originalPolicy = StrictMode.allowThreadDiskWrites();
  try {
    CHECK_EXECUTOR.checkAndReturnResults(view);
  } finally {
    StrictMode.setThreadPolicy(originalPolicy);
  }
}
 
Example #6
Source File: NewPostTest.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
/**
 * Click the 'Log Out' overflow menu if it exists (which would mean we're signed in).
 */
private void logOutIfPossible() {
    try {
        openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getTargetContext());
        onView(withText(R.string.menu_logout)).perform(click());
    } catch (NoMatchingViewException e) {
        // Ignore exception since we only want to do this operation if it's easy.
    }

}
 
Example #7
Source File: AuthenticatorActivityTest.java    From google-authenticator-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testOptionsMenuSwitchUiModeHidedInBeginSetupScreenOnDarkMode() {
  Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
  setDarkModeEnabled(context, true);

  activityTestRule.launchActivity(null);

  onView(isRoot()).perform(pressMenuKey());
  try {
    onView(withText(context.getString(R.string.switch_ui_mode_light))).perform(click());
    Assert.fail("Switch UI mode option should be hidden in begin setup screen");
  } catch (NoMatchingViewException ignored) {
    // Expected.
  }
}
 
Example #8
Source File: AuthenticatorActivityTest.java    From google-authenticator-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testOptionsMenuSwitchUiModeHidedInBeginSetupScreenOnLightMode() {
  Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();

  activityTestRule.launchActivity(null);

  onView(isRoot()).perform(pressMenuKey());
  try {
    onView(withText(context.getString(R.string.switch_ui_mode_dark))).perform(click());
    Assert.fail("Switch UI mode option should be hidden in begin setup screen");
  } catch (NoMatchingViewException ignored) {
    // Expected.
  }
}
 
Example #9
Source File: ViewFinderImplTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
@UiThreadTest
public void getView_missing() {
  ViewFinder finder = new ViewFinderImpl(nullValue(View.class), testViewProvider);
  expectedException.expect(NoMatchingViewException.class);
  finder.getView();
}
 
Example #10
Source File: DefaultFailureHandlerTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
/**
 * Test only passes if run in isolation. Unless Gradle supports a single instrumentation per test
 * this test is ignored"
 */
@Test
public void noMatchingViewException() {
  expectedException.expect(NoMatchingViewException.class);
  expectedException.expect(stackTraceContainsThisClass());
  onView(withMatchesThatReturns(false)).check(matches(not(isDisplayed())));
}
 
Example #11
Source File: DefaultFailureHandlerTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void customAssertionError() {
  expectedException.expect(AssertionFailedError.class);
  expectedException.expectCause(stackTraceContainsThisClass());
  onView(isRoot())
      .check(
          new ViewAssertion() {
            @Override
            public void check(View view, NoMatchingViewException noViewFoundException) {
              fail();
            }
          });
}
 
Example #12
Source File: PositionAssertions.java    From android-test with Apache License 2.0 5 votes vote down vote up
static View findView(final Matcher<View> toView, View root) {
  Preconditions.checkNotNull(toView);
  Preconditions.checkNotNull(root);
  final Predicate<View> viewPredicate =
      new Predicate<View>() {
        @Override
        public boolean apply(View input) {
          return toView.matches(input);
        }
      };
  Iterator<View> matchedViewIterator =
      Iterables.filter(breadthFirstViewTraversal(root), viewPredicate).iterator();
  View matchedView = null;
  while (matchedViewIterator.hasNext()) {
    if (matchedView != null) {
      // Ambiguous!
      throw new AmbiguousViewMatcherException.Builder()
          .withRootView(root)
          .withViewMatcher(toView)
          .withView1(matchedView)
          .withView2(matchedViewIterator.next())
          .withOtherAmbiguousViews(Iterators.toArray(matchedViewIterator, View.class))
          .build();
    } else {
      matchedView = matchedViewIterator.next();
    }
  }
  if (matchedView == null) {
    throw new NoMatchingViewException.Builder()
        .withViewMatcher(toView)
        .withRootView(root)
        .build();
  }
  return matchedView;
}
 
Example #13
Source File: PositionAssertions.java    From android-test with Apache License 2.0 5 votes vote down vote up
static ViewAssertion relativePositionOf(
    final Matcher<View> viewMatcher, final Position position) {
  checkNotNull(viewMatcher);
  return new ViewAssertion() {
    @Override
    public void check(final View foundView, NoMatchingViewException noViewException) {
      StringDescription description = new StringDescription();
      if (noViewException != null) {
        description.appendText(
            String.format(
                Locale.ROOT,
                "' check could not be performed because view '%s' was not found.\n",
                noViewException.getViewMatcherDescription()));
        Log.e(TAG, description.toString());
        throw noViewException;
      } else {
        // TODO: describe the foundView matcher instead of the foundView itself.
        description
            .appendText("View:")
            .appendText(HumanReadables.describe(foundView))
            .appendText(" is not ")
            .appendText(position.toString())
            .appendText(" view ")
            .appendText(viewMatcher.toString());
        assertThat(
            description.toString(),
            isRelativePosition(
                foundView, findView(viewMatcher, getTopViewGroup(foundView)), position),
            is(true));
      }
    }
  };
}
 
Example #14
Source File: ViewAssertions.java    From android-test with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void check(View view, NoMatchingViewException noViewException) {
  Preconditions.checkNotNull(view);

  final Predicate<View> viewPredicate =
      new Predicate<View>() {
        @Override
        public boolean apply(View input) {
          return selector.matches(input);
        }
      };

  Iterator<View> selectedViewIterator =
      Iterables.filter(breadthFirstViewTraversal(view), viewPredicate).iterator();

  List<View> nonMatchingViews = new ArrayList<>();
  while (selectedViewIterator.hasNext()) {
    View selectedView = selectedViewIterator.next();

    if (!matcher.matches(selectedView)) {
      nonMatchingViews.add(selectedView);
    }
  }

  if (nonMatchingViews.size() > 0) {
    String errorMessage =
        HumanReadables.getViewHierarchyErrorMessage(
            view,
            nonMatchingViews,
            String.format(
                Locale.ROOT,
                "At least one view did not match the required matcher: %s",
                matcher),
            "****DOES NOT MATCH****");
    throw new AssertionFailedError(errorMessage);
  }
}
 
Example #15
Source File: ViewAssertions.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Override
public void check(View view, NoMatchingViewException noView) {
  if (view != null) {
    assertThat(
        "View is present in the hierarchy: " + HumanReadables.describe(view), true, is(false));
  }
}
 
Example #16
Source File: AccessibilityChecksIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckWithNonNullMatchingViewException_throwsNoMatchingViewException() {
  try {
    onView(withText("There is no view with this text!")).check(accessibilityAssertion());
    fail("Should have thrown a NoMatchingViewException");
  } catch (NoMatchingViewException expected) {
  }
}
 
Example #17
Source File: MainActivityTest.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
/**
 * Click the 'Log Out' overflow menu if it exists (which would mean we're signed in).
 */
private void logOutIfPossible() {
    try {
        openActionBarOverflowOrOptionsMenu(getTargetContext());
        onView(withText(R.string.log_out)).perform(click());
    } catch (NoMatchingViewException e) {
        // Ignore exception since we only want to do this operation if it's easy.
    }

}
 
Example #18
Source File: PollingTimeoutIdler.java    From samples-android with Apache License 2.0 5 votes vote down vote up
public PollingTimeoutIdler(ViewInteraction viewInteraction, ViewAssertion viewAssertion, long timeout) {
    mViewAssertion = viewAssertion;
    mTimeout = timeout;
    mStartTime = System.currentTimeMillis();

    viewInteraction.check(new ViewAssertion() {
        @Override
        public void check(View view, NoMatchingViewException noViewFoundException) {
            mTestView = view;
        }
    });
}
 
Example #19
Source File: EmailPasswordTest.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
private void signOutIfPossible() {
    try {
        onView(allOf(withId(R.id.signOutButton), withText(R.string.sign_out), isDisplayed()))
                .perform(click());
    } catch (NoMatchingViewException e) {
        // Ignore
    }

}
 
Example #20
Source File: AnonymousTest.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
private void signOutIfPossible() {
    try {
        onView(allOf(withId(R.id.buttonAnonymousSignOut), isDisplayed()))
                .perform(click());
    } catch (NoMatchingViewException e) {
        // Ignore
    }

}
 
Example #21
Source File: MainActivityTest.java    From quickstart-android with Apache License 2.0 5 votes vote down vote up
private void selectFavoriteFoodIfPossible(String food) {
    try{
        ViewInteraction appCompatTextView = onView(
                allOf(withId(android.R.id.text1), withText(food),
                        withParent(allOf(withId(R.id.select_dialog_listview),
                                withParent(withId(R.id.contentPanel)))),
                        isDisplayed()));
        appCompatTextView.perform(click());
    } catch (NoMatchingViewException e) {
        // This is ok
    }
}
 
Example #22
Source File: AccessibilityChecksIntegrationTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckWithNonNullMatchingViewException_throwsNoMatchingViewException() {
  try {
    onView(withText("There is no view with this text!")).check(accessibilityAssertion());
    fail("Should have thrown a NoMatchingViewException");
  } catch (NoMatchingViewException expected) {
  }
}
 
Example #23
Source File: UITests.java    From aptoide-client-v8 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * if it shows the next_icon button it means the user is opening Aptoide for the first time and
 * it's on the Wizard
 *
 * @return
 */
protected static boolean isFirstTime() {
  try {
    onView(withId(R.id.next_icon)).check(matches(isDisplayed()));
    return true;
  } catch (NoMatchingViewException e) {
    return false;
  }
}
 
Example #24
Source File: EspressoTestUtils.java    From Kore with Apache License 2.0 5 votes vote down vote up
/**
 * Clicks a menu item regardless if it is in the overflow menu or
 * visible as icon in the action bar
 * @param activity
 * @param name Name of the menu item in the overflow menu
 * @param resourceId Resource identifier of the menu item
 */
public static void clickMenuItem(Activity activity, String name, int resourceId) {
    try {
        onView(withId(resourceId)).perform(click());
    } catch (NoMatchingViewException e) {
        openActionBarOverflowOrOptionsMenu(activity);
        //Use onData as item might not be visible in the View without scrolling
        onData(allOf(
                Matchers.withMenuTitle(name)))
                .perform(click());
    }
}
 
Example #25
Source File: EspressoTestUtils.java    From Kore with Apache License 2.0 5 votes vote down vote up
/**
 * Clears the search query by pressing the X button
 * @param activity
 */
public static void clearSearchQueryXButton(Activity activity) {
    try {
        onView(withId(R.id.search_close_btn)).perform(click());
    } catch (NoMatchingViewException e) {
        EspressoTestUtils.clickMenuItem(activity, activity.getString(R.string.action_search), R.id.action_search);
        onView(withId(R.id.search_close_btn)).perform(click());
    }
    Espresso.closeSoftKeyboard();
}
 
Example #26
Source File: WebAssertion.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
  if (null == view) {
    throw noViewFoundException;
  } else if (!(view instanceof WebView)) {
    throw new RuntimeException(view + ": is not a WebView!");
  } else {
    webAssertion.checkResult((WebView) view, result);
  }
}
 
Example #27
Source File: WebViewAssertionsTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void testWebContent_NoViewFound() {
  try {
    onWebView(withText("not there"))
        .check(
            webContent(
                elementById(
                    "info", withTextContent("Enter input and click the Submit button."))));
    fail("Previous call should have failed");
  } catch (NoMatchingViewException expected) {
  }
}
 
Example #28
Source File: Intents.java    From android-test with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that the given matcher matches a specified number of intents sent by the application
 * under test. This is an equivalent of verify(mock, times(num)) in Mockito. Verification does not
 * have to occur in the same order as the intents were sent. Intents are recorded from the time
 * that Intents.init is called.
 *
 * @param matcher the {@link Matcher} to be applied to captured intents
 * @throws AssertionFailedError if the given {@link Matcher} did not match the expected number of
 *     recorded intents
 */
public static void intended(
    final Matcher<Intent> matcher, final VerificationMode verificationMode) {
  checkNotNull(defaultInstance, "Intents not initialized. Did you forget to call init()?");
  Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
  instrumentation.waitForIdleSync();
  if (resumedActivitiesExist(instrumentation)) {
    // Running through Espresso to take advantage of its synchronization mechanism.
    onView(isRoot())
        .check(
            new ViewAssertion() {
              @Override
              public void check(View view, NoMatchingViewException noViewFoundException) {
                defaultInstance.internalIntended(matcher, verificationMode, recordedIntents);
              }
            });
  } else {
    // No activities are resumed, so we don't need Espresso's synchronization.
    PropogatingRunnable intendedRunnable =
        new PropogatingRunnable(
            new Runnable() {
              @Override
              public void run() {
                defaultInstance.internalIntended(matcher, verificationMode, recordedIntents);
              }
            });
    instrumentation.runOnMainSync(intendedRunnable);
    instrumentation.waitForIdleSync();
    intendedRunnable.checkException();
  }
}
 
Example #29
Source File: BrowserScreenScreenshots.java    From focus-android with Mozilla Public License 2.0 4 votes vote down vote up
private void takeScreenshotsOfBrowsingView() {
    onView(withId(R.id.urlView))
            .check(matches(isDisplayed()));

    // click yes, then go into search dialog and change to twitter, or create twitter engine
    // If it does not exist (In order to get search unavailable dialog)
    openSettings();
    onView(withText(R.string.preference_category_search))
            .perform(click());
    onView(allOf(withText(R.string.preference_search_engine_label),
            withResourceName("title")))
            .perform(click());
    onView(withText(R.string.preference_search_installed_search_engines))
            .check(matches(isDisplayed()));

   try {
       onView(withText("Twitter"))
               .check(matches(isDisplayed()))
               .perform(click());
   } catch (NoMatchingViewException doesnotexist) {
       final String addEngineLabel = getString(R.string.preference_search_add2);
       onView(withText(addEngineLabel))
               .check(matches(isEnabled()))
               .perform(click());
       onView(withId(R.id.edit_engine_name))
               .check(matches(isEnabled()));
       onView(withId(R.id.edit_engine_name))
               .perform(replaceText("twitter"));
       onView(withId(R.id.edit_search_string))
               .perform(replaceText("https://twitter.com/search?q=%s"));
       onView(withId(R.id.menu_save_search_engine))
               .check(matches(isEnabled()))
               .perform(click());
   }

    device.pressBack();
    onView(allOf(withText(R.string.preference_search_engine_label),
            withResourceName("title")))
            .check(matches(isDisplayed()));
    device.pressBack();
    onView(withText(R.string.preference_category_search))
            .check(matches(isDisplayed()));
    device.pressBack();

    onView(withId(R.id.urlView))
            .check(matches(isDisplayed()))
            .check(matches(hasFocus()))
            .perform(click(), replaceText(webServer.url("/").toString()));
    try {
        onView(withId(R.id.enable_search_suggestions_button))
                .check(matches(isDisplayed()));
        Screengrab.screenshot("Enable_Suggestion_dialog");
        onView(withId(R.id.enable_search_suggestions_button))
                .perform(click());
        Screengrab.screenshot("Suggestion_unavailable_dialog");
        onView(withId(R.id.dismiss_no_suggestions_message))
                .perform(click());
    } catch (AssertionError dne) { }

    onView(withId(R.id.urlView))
            .check(matches(isDisplayed()))
            .check(matches(hasFocus()))
            .perform(pressImeActionButton());

    device.findObject(new UiSelector()
            .resourceId(TestHelper.getAppName() + ":id/webview")
            .enabled(true))
            .waitForExists(waitingTime);

    onView(withId(R.id.display_url))
            .check(matches(isDisplayed()))
            .check(matches(withText(containsString(webServer.getHostName()))));

    // Check add link to autocomplete text
    onView(withId(R.id.display_url)).perform(click());
    onView(withId(R.id.addToAutoComplete))
            .check(matches(isDisplayed()));
    Screengrab.screenshot("Addlink_autocomplete");
    onView(withId(R.id.addToAutoComplete))
            .perform(click());
    Screengrab.screenshot("new_customURL_popup");
    onView(withId(R.id.display_url)).perform(click());
    onView(withId(R.id.addToAutoComplete))
            .perform(click());
    Screengrab.screenshot("customURL_alreadyexists_popup");
}
 
Example #30
Source File: PositionAssertionsTest.java    From android-test with Apache License 2.0 4 votes vote down vote up
@Test
public void findView_NotFound() {
  View root = setUpViewHierarchy();
  expectedException.expect(NoMatchingViewException.class);
  findView(withText("does not exist"), root);
}