Подтвердить что ты не робот

Android Espresso - Как проверить подсказку EditText?

Я начинаю играть с Espresso, мои основные тесты работают. Теперь, пытаясь выяснить, как проверить, что мой текст редактирования имеет конкретный текст подсказки? Спасибо.

onView(withId(R.id.locationInput)).check(matches...?)

4b9b3361

Ответ 1

Похоже, я понял это. В принципе, вам нужно создать собственный собеседник:

public static Matcher<View> withHint(final String expectedHint) {
    return new TypeSafeMatcher<View>() {

        @Override
        public boolean matchesSafely(View view) {
            if (!(view instanceof EditText)) {
                return false;
            }

            String hint = ((EditText) view).getHint().toString();

            return expectedHint.equals(hint);
        }

        @Override
        public void describeTo(Description description) {
        }
    };
}

Затем вы можете использовать его:

onView(withId(R.id.locationInput)).check(matches(withHint("Location (Optional)")));

Ответ 2

Так как Espresso 2.0 использует только внутренний ViewMatcher withHint:

onView(withId(R.id.locationInput)).check(matches(withHint("your_hint")))

Ответ 3

Существует несколько иной способ сделать это. В моем случае вы проверяете, что строка не имеет значения null, прежде чем передать ее в соответствие (как описано в примерах Espresso). А также в коде ниже вам не нужен Rid EditText с этим подсказкой. Вы просто проверяете, отображается ли подсказка с помощью "hintText":

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

public final class Matchers {

    public static Matcher<View> withItemHint(String hintText) {
        // use preconditions to fail fast when a test is creating an invalid matcher.
        checkArgument(!(hintText.equals(null)));
        return withItemHint(is(hintText));
    }

    public static Matcher<View> withItemHint(final Matcher<String> matcherText) {
        // use preconditions to fail fast when a test is creating an invalid matcher.
        checkNotNull(matcherText);
        return new BoundedMatcher<View, EditText>(EditText.class) {      

            @Override
            public void describeTo(Description description) {
                description.appendText("with item hint: " + matcherText);
            }

            @Override
            protected boolean matchesSafely(EditText editTextField) {
                return matcherText.matches(editTextField.getHint().toString());
            }
        };
    }
}

Использование:

import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isDisplayed;
import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
import static com.your.package.withMatcher.withItemHint;
.
.
.
onView(withItemHint(someHintString)).check(matches(isDisplayed()));

Ответ 4

Я создал Matcher, который поддерживает передачу resourceId вместо строки

public static Matcher<View> withHint(final int resourceId) {
     return new BoundedMatcher<View, TextView>(TextView.class) {
     private String resourceName = null;
     private String expectedHint = null;

     @Override
     public boolean matchesSafely(TextView editText) {
        if (null == expectedHint) {
          try {
            expectedHint = editText.getResources().getString(resourceId);
            resourceName = editText.getResources().getResourceEntryName(resourceId);
          } catch (Resources.NotFoundException ignored) {
            /* view could be from a context unaware of the resource id. */
          }
        }

        if (null != expectedHint) {
          return expectedHint.equals(editText.getHint());
        } else {
          return false;
        }
      }

      @Override
      public void describeTo(Description description) {
        description.appendText("with string from resource id: ");
        description.appendValue(resourceId);
        if (null != resourceName) {
          description.appendText("[");
          description.appendText(resourceName);
          description.appendText("]");
        }
        if (null != expectedHint) {
          description.appendText(" value: ");
          description.appendText(expectedHint);
        }
      }
    };
  }

Это репликация эспрессо с тестером, указанным Валерой Захаров (withText (resourceId)