androidx.test.espresso.ViewAssertion Java Examples

The following examples show how to use androidx.test.espresso.ViewAssertion. 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: EspressoRemoteTest.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Test
public void remoteInteractionStrategy_addsViewAssertionBinders_fromBundle() {
  Matcher viewMatcherMock = Mockito.mock(Matcher.class);
  Matcher rootMatcherMock = Mockito.mock(Matcher.class);
  IBinder binderMock = Mockito.mock(IBinder.class);
  Bindable bindableMock = Mockito.mock(Bindable.class);
  String bindableViewAssertionId = BindableViewAssertion.class.getSimpleName();
  when(bindableMock.getId()).thenReturn(bindableViewAssertionId);
  ViewAssertion bindableViewAssertion = new BindableViewAssertion(bindableMock);

  InteractionRequest interactionRequest =
      new InteractionRequest(rootMatcherMock, viewMatcherMock, null, bindableViewAssertion);

  Bundle bundle = new Bundle();
  bundle.putParcelable(bindableMock.getId(), new ParcelableIBinder(binderMock));
  RemoteInteractionStrategy.from(interactionRequest, bundle);

  verify(bindableMock).setIBinder(binderMock);
}
 
Example #2
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 #3
Source File: TextInputLayoutTest.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
private static ViewAssertion isBoxCornerRadiusTopEnd(final float boxCornerRadiusTopEnd) {
  return (view, noViewFoundException) -> {
    assertTrue(view instanceof TextInputLayout);
    assertEquals(
        boxCornerRadiusTopEnd, ((TextInputLayout) view).getBoxCornerRadiusTopEnd(), 0.01);
  };
}
 
Example #4
Source File: RemoteViewAssertionsTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void noOverlaps_transformationToProto() {
  ViewAssertion viewAssertion = noOverlaps();

  NoOverlapsViewAssertionProto viewAssertionProto =
      (NoOverlapsViewAssertionProto) new GenericRemoteMessage(viewAssertion).toProto();

  assertThat(viewAssertionProto, notNullValue());
}
 
Example #5
Source File: RemoteViewAssertionsTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void noOverlaps_transformationFromProto() {
  ViewAssertion viewAssertion = noOverlaps();

  NoOverlapsViewAssertionProto viewAssertionProto =
      (NoOverlapsViewAssertionProto) new GenericRemoteMessage(viewAssertion).toProto();
  ViewAssertion viewAssertionFromProto =
      (ViewAssertion) GenericRemoteMessage.FROM.fromProto(viewAssertionProto);

  assertThat(viewAssertionFromProto, instanceOf(NoOverlapsViewAssertion.class));
}
 
Example #6
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 #7
Source File: TextInputLayoutIconsTest.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
private static ViewAssertion isPasswordToggledVisible(final boolean isToggledVisible) {
  return (view, noViewFoundException) -> {
    assertTrue(view instanceof TextInputLayout);
    EditText editText = ((TextInputLayout) view).getEditText();
    TransformationMethod transformationMethod = editText.getTransformationMethod();
    if (isToggledVisible) {
      assertNull(transformationMethod);
    } else {
      assertEquals(PasswordTransformationMethod.getInstance(), transformationMethod);
    }
  };
}
 
Example #8
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 #9
Source File: RemoteViewAssertionsTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void selectedDescendantsMatch_transformationToProto() {
  ViewAssertion viewAssertion =
      selectedDescendantsMatch(withText("no content description"), hasContentDescription());

  SelectedDescendantsMatchViewAssertionProto viewAssertionProto =
      (SelectedDescendantsMatchViewAssertionProto)
          new GenericRemoteMessage(viewAssertion).toProto();

  assertThat(viewAssertionProto, notNullValue());
}
 
Example #10
Source File: LayoutAssertions.java    From android-test with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link ViewAssertion} that asserts that descendant objects assignable to TextView or
 * ImageView do not overlap each other.
 *
 * <p>Example: {@code onView(rootView).check(noOverlaps());}
 */
public static ViewAssertion noOverlaps() {
  return noOverlaps(
      allOf(
          withEffectiveVisibility(Visibility.VISIBLE),
          anyOf(isAssignableFrom(TextView.class), isAssignableFrom(ImageView.class))));
}
 
Example #11
Source File: RemoteViewAssertionsTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void doesNotExist_transformationFromProto() {
  ViewAssertion viewAssertion = doesNotExist();

  DoesNotExistViewAssertionProto viewAssertionProto =
      (DoesNotExistViewAssertionProto) new GenericRemoteMessage(viewAssertion).toProto();
  ViewAssertion viewAssertionFromProto =
      (ViewAssertion) GenericRemoteMessage.FROM.fromProto(viewAssertionProto);

  assertThat(viewAssertionFromProto, instanceOf(DoesNotExistViewAssertion.class));
}
 
Example #12
Source File: RemoteViewAssertionsTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void doesNotExist_transformationToProto() {
  ViewAssertion viewAssertion = doesNotExist();

  DoesNotExistViewAssertionProto viewAssertionProto =
      (DoesNotExistViewAssertionProto) new GenericRemoteMessage(viewAssertion).toProto();

  assertThat(viewAssertionProto, notNullValue());
}
 
Example #13
Source File: RemoteViewAssertionsTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void matches_transformationToProto() {
  View view = new View(getInstrumentation().getContext());
  ViewAssertion viewAssertion = matches(withId(view.getId()));

  MatchesViewAssertionProto viewAssertionProto =
      (MatchesViewAssertionProto) new GenericRemoteMessage(viewAssertion).toProto();

  assertThat(viewAssertionProto, notNullValue());
}
 
Example #14
Source File: RemoteViewAssertionsTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void selectedDescendantsMatch_transformationFromProto() {
  ViewAssertion viewAssertion =
      selectedDescendantsMatch(withText("no content description"), hasContentDescription());

  SelectedDescendantsMatchViewAssertionProto viewAssertionProto =
      (SelectedDescendantsMatchViewAssertionProto)
          new GenericRemoteMessage(viewAssertion).toProto();
  ViewAssertion viewAssertionFromProto =
      (ViewAssertion) GenericRemoteMessage.FROM.fromProto(viewAssertionProto);

  assertThat(viewAssertionFromProto, instanceOf(SelectedDescendantsMatchViewAssertion.class));
}
 
Example #15
Source File: NoopRemoteInteraction.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Override
public Callable<Void> createRemoteCheckCallable(
    Matcher<Root> rootMatcher,
    Matcher<View> viewMatcher,
    Map<String, IBinder> iBinders,
    ViewAssertion viewAssertion) {
  return new Callable<Void>() {
    @Override
    public Void call() throws Exception {
      throw new NoRemoteEspressoInstanceException("No remote instances available");
    }
  };
}
 
Example #16
Source File: EspressoRemote.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Callable<Void> createRemoteCheckCallable(
    final Matcher<Root> rootMatcher,
    final Matcher<View> viewMatcher,
    final Map<String, IBinder> iBinders,
    final ViewAssertion viewAssertion) {

  return createRemoteInteraction(
      new Runnable() {
        @Override
        public void run() {
          Log.i(
              TAG,
              String.format(
                  Locale.ROOT,
                  "Attempting to run check interaction on a remote process "
                      + "for ViewAssertion: %s",
                  viewAssertion));
          InteractionRequest interactionRequest =
              new InteractionRequest.Builder()
                  .setRootMatcher(rootMatcher)
                  .setViewMatcher(viewMatcher)
                  .setViewAssertion(viewAssertion)
                  .build();

          // Send remote interaction request to other Espresso instances
          initiateRemoteCall(interactionRequest.toProto().toByteArray(), iBinders);
        }
      });
}
 
Example #17
Source File: EspressoRemote.java    From android-test with Apache License 2.0 5 votes vote down vote up
public static RemoteInteractionStrategy from(
    @NonNull InteractionRequest interactionRequest, Bundle bundle) {
  checkNotNull(interactionRequest, "interactionRequest cannot be null!");
  logDebugWithProcess(
      TAG,
      "Creating RemoteInteractionStrategy from values:\n"
          + "RootMatcher: %s\n"
          + "ViewMatcher: %s\n"
          + "ViewAction: %s\n"
          + "View Assertion: %s",
      interactionRequest.getRootMatcher(),
      interactionRequest.getViewMatcher(),
      interactionRequest.getViewAction(),
      interactionRequest.getViewAssertion());

  // If a view action is set on the interaction request, perform an action
  if (interactionRequest.getViewAction() != null) {
    // Additionally check if the action is Bindable and set the IBinder
    ViewAction viewAction = interactionRequest.getViewAction();
    setIBinderFromBundle(viewAction, bundle);

    return new OnViewPerformStrategy(
        interactionRequest.getRootMatcher(), interactionRequest.getViewMatcher(), viewAction);
  } else {
    // Additionally check if the assertion is Bindable and set the IBinder
    ViewAssertion viewAssertion = interactionRequest.getViewAssertion();
    setIBinderFromBundle(viewAssertion, bundle);
    // Otherwise a check a view assertion
    return new OnViewCheckStrategy(
        interactionRequest.getRootMatcher(),
        interactionRequest.getViewMatcher(),
        viewAssertion);
  }
}
 
Example #18
Source File: InteractionRequest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Override
public InteractionRequest fromProto(InteractionRequestProto interactionRequestProto) {
  Builder interactionRequestBuilder = new Builder();
  interactionRequestBuilder
      .setRootMatcher(
          TypeProtoConverters.<Matcher<Root>>anyToType(
              interactionRequestProto.getRootMatcher()))
      .setViewMatcher(
          TypeProtoConverters.<Matcher<View>>anyToType(
              interactionRequestProto.getViewMatcher()));

  int actionOrAssertionCaseNumber =
      interactionRequestProto.getActionOrAssertionCase().getNumber();

  if (ActionOrAssertionCase.VIEW_ACTION.getNumber() == actionOrAssertionCaseNumber) {
    interactionRequestBuilder.setViewAction(
        TypeProtoConverters.<ViewAction>anyToType(
            interactionRequestProto.getViewAction()));
  }

  if (ActionOrAssertionCase.VIEW_ASSERTION.getNumber() == actionOrAssertionCaseNumber) {
    interactionRequestBuilder.setViewAssertion(
        TypeProtoConverters.<ViewAssertion>anyToType(
            interactionRequestProto.getViewAssertion()));
  }
  return interactionRequestBuilder.build();
}
 
Example #19
Source File: InteractionRequest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
InteractionRequest(
    @Nullable Matcher<Root> rootMatcher,
    @Nullable Matcher<View> viewMatcher,
    @Nullable ViewAction viewAction,
    @Nullable ViewAssertion viewAssertion) {
  this.rootMatcher = rootMatcher;
  this.viewMatcher = viewMatcher;
  this.viewAction = viewAction;
  this.viewAssertion = viewAssertion;
}
 
Example #20
Source File: ViewActions.java    From android-test with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a {@code ViewAssertion} to be run every time a {@code ViewAction} in this class is
 * performed. The assertion will be run prior to performing the action.
 *
 * @param name a name of the assertion to be added
 * @param viewAssertion a {@code ViewAssertion} to be added
 * @throws IllegalArgumentException if the name/viewAssertion pair is already contained in the
 *     global assertions.
 */
public static void addGlobalAssertion(String name, ViewAssertion viewAssertion) {
  checkNotNull(name);
  checkNotNull(viewAssertion);
  Pair<String, ViewAssertion> vaPair = new Pair<String, ViewAssertion>(name, viewAssertion);
  checkArgument(
      !globalAssertions.contains(vaPair),
      "ViewAssertion with name %s is already in the global assertions!",
      name);
  globalAssertions.add(vaPair);
}
 
Example #21
Source File: ViewActions.java    From android-test with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the given assertion from the set of assertions to be run before actions are performed.
 *
 * @param viewAssertion the assertion to remove
 * @throws IllegalArgumentException if the name/viewAssertion pair is not already contained in the
 *     global assertions.
 */
public static void removeGlobalAssertion(ViewAssertion viewAssertion) {
  boolean removed = false;
  for (Pair<String, ViewAssertion> vaPair : globalAssertions) {
    if (viewAssertion != null && viewAssertion.equals(vaPair.second)) {
      removed = removed || globalAssertions.remove(vaPair);
    }
  }
  checkArgument(removed, "ViewAssertion was not in global assertions!");
}
 
Example #22
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 #23
Source File: RemoteViewAssertionsTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void matches_transformationFromProto() {
  View view = new View(getInstrumentation().getContext());
  ViewAssertion viewAssertion = matches(withId(view.getId()));

  MatchesViewAssertionProto viewAssertionProto =
      (MatchesViewAssertionProto) new GenericRemoteMessage(viewAssertion).toProto();

  ((MatchesViewAssertion) GenericRemoteMessage.FROM.fromProto(viewAssertionProto))
      .viewMatcher.matches(view);
}
 
Example #24
Source File: TextInputLayoutTest.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
private static ViewAssertion isCutoutOpen(final boolean open) {
  return (view, noViewFoundException) -> {
    assertTrue(view instanceof TextInputLayout);
    assertEquals(open, ((TextInputLayout) view).cutoutIsOpen());
  };
}
 
Example #25
Source File: TextInputLayoutTest.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
private static ViewAssertion isHintExpanded(final boolean expanded) {
  return (view, noViewFoundException) -> {
    assertTrue(view instanceof TextInputLayout);
    assertEquals(expanded, ((TextInputLayout) view).isHintExpanded());
  };
}
 
Example #26
Source File: TextInputLayoutTest.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
private static ViewAssertion isBoxStrokeColor(@ColorInt final int boxStrokeColor) {
  return (view, noViewFoundException) -> {
    assertTrue(view instanceof TextInputLayout);
    assertEquals(boxStrokeColor, ((TextInputLayout) view).getBoxStrokeColor());
  };
}
 
Example #27
Source File: EspressoRemote.java    From android-test with Apache License 2.0 4 votes vote down vote up
public OnViewCheckStrategy(
    Matcher<Root> rootMatcher, Matcher<View> viewMatcher, ViewAssertion viewAssertion) {
  this.rootMatcher = rootMatcher;
  this.viewMatcher = viewMatcher;
  this.viewAssertion = viewAssertion;
}
 
Example #28
Source File: TextInputLayoutTest.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
private static ViewAssertion isBoxStrokeErrorColor(final ColorStateList boxStrokeColor) {
  return (view, noViewFoundException) -> {
    assertTrue(view instanceof TextInputLayout);
    assertEquals(boxStrokeColor, ((TextInputLayout) view).getBoxStrokeErrorColor());
  };
}
 
Example #29
Source File: TextInputLayoutTest.java    From material-components-android with Apache License 2.0 4 votes vote down vote up
private static ViewAssertion isBoxBackgroundColor(@ColorInt final int boxBackgroundColor) {
  return (view, noViewFoundException) -> {
    assertTrue(view instanceof TextInputLayout);
    assertEquals(boxBackgroundColor, ((TextInputLayout) view).getBoxBackgroundColor());
  };
}
 
Example #30
Source File: CheckDescendantViewAction.java    From EspressoDescendantActions with Apache License 2.0 4 votes vote down vote up
CheckDescendantViewAction(Matcher<View> viewMatcher, ViewAssertion viewAssertion) {
    this.viewMatcher = viewMatcher;
    this.viewAssertion = viewAssertion;
}