Android.Эспрессо: Как проверить прописные буквы TextView? - PullRequest
0 голосов
/ 12 июня 2018

Android 3.1.2, Gradle 4.4, Java 1.8, Espresso 3.0.1.

Вот фрагмент моего макета XML:

  <TextView
            android:id="@+id/loginTextView"
            android:layout_width="255dp"
            android:layout_height="60dp"
            android:layout_marginBottom="15dp"
            android:background="@drawable/sign_in_login_bg"
            android:gravity="center"
            android:onClick="@{ () -> presenter.doLogin()}"
            android:text="@string/login"
            android:textAllCaps="true"
            android:textColor="@android:color/white"
            app:layout_constraintBottom_toTopOf="@+id/registerTextView"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />

Вот результат: enter image description here

Как видно из текста, TextView показан в верхнем регистре.Ницца.Нет, я хочу написать эспрессо-тест, проверяющий, что textView включен в верхнем регистре .Итак, вот мой инструментальный тест Espresso:

@Test
    public void loginTextViewUppercase() {
        onView(withId(R.id.loginTextView)).check(matches(withUppercaseText(R.string.login)));
}


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

            @Override
            public boolean matchesSafely(TextView textView) {
                if (null == expectedText) {
                    try {
                        expectedText = textView.getResources().getString(resourceId).toUpperCase();
                        resourceName = textView.getResources().getResourceEntryName(resourceId);
                    } catch (Resources.NotFoundException ignored) {
                        /* view could be from a context unaware of the resource id. */
                    }
                }
                CharSequence actualText = textView.getText();
                if (null != expectedText && null != actualText) {
                         return expectedText.equals(actualText.toString());
                } else {
                    return false;
                }
            }

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

Но когда я запускаю тест loginTextViewUppercase Я получаю ошибку:

android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with uppercase string from resource id: <2131624014>' doesn't match the selected view.
Expected: with uppercase string from resource id: <2131624014>[login] value: LOGIN
Got: "AppCompatTextView{id=2131296429, res-name=loginTextView, visibility=VISIBLE, width=765, height=180, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, layout-params=android.support.constraint.ConstraintLayout$LayoutParams@7f5fced, tag=null, root-is-layout-requested=false, has-input-connection=false, x=158.0, y=1283.0, text=Login, input-type=0, ime-target=false, has-links=false}"

at dalvik.system.VMStack.getThreadStackTrace(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:580)
at android.support.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:90)

Ответы [ 2 ]

0 голосов
/ 12 июня 2018

Вы можете извлечь метод преобразования из самого TextView, чтобы проверить, что это textAllCaps.В этом случае вам не нужно добавлять какие-либо изменения в код продукта:

        @Override
        public boolean matchesSafely(TextView textView) {
            if (null == expectedText) {
                try {
                    expectedText = textView.getResources().getString(resourceId).toUpperCase();
                    resourceName = textView.getResources().getResourceEntryName(resourceId);
                } catch (Resources.NotFoundException ignored) {
                    /* view could be from a context unaware of the resource id. */
                }
            }
            String actualText = textView.getText().toString();
            if (null != expectedText) {
                     TransformationMethod currentMethod = textView.getTransformationMethod();
                     //if the transformation is AllCapsTransformationMethod then it means that the text is uppercase
                     return expectedText.equalsIgnoreCase(actualText) && currentMethod != null && AllCapsTransformationMethod.class.getClass().isInstance(currentMethod.getClass());
            } else {
                return false;
            }
        }
0 голосов
/ 12 июня 2018

это решено для меня loginTextView.setText (strings.toUpperCase ());

...