Android.Эспрессо: не могу проверить фон - PullRequest
0 голосов
/ 11 июня 2018

Windows 10 (64 бит), Android Studio 3.1.2, Gradle 4.4, Java 1.8.

Здесь мой макет 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"                              
            app:layout_constraintBottom_toTopOf="@+id/registerTextView"
            app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

Здесь @ drawable / sign_in_login_bg

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/color_primary" />
    <corners android:radius="@dimen/text_view_rounded_corner_radius" />
</shape>

Я хочу написать эспрессо-тест, который проверяет, что loginTextView имеет фон @ drawable / sign_in_login_bg

Так что я пишу пользовательское сопоставление:

import org.hamcrest.Matcher;
      public static Matcher<View> withBackground(final int expectedResourceId) {

            return new BoundedMatcher<View, View>(View.class) {

                @Override
                public boolean matchesSafely(View view) {
                    return sameBitmap(view.getContext(), view.getBackground(), expectedResourceId);
                }

                @Override
                public void describeTo(Description description) {
                    description.appendText("has background resource " + expectedResourceId);
                }
            };
    }

Вот метод sameBitmap :

private static boolean sameBitmap(Context context, Drawable drawable, int expectedId) {
        Drawable expectedDrawable = ContextCompat.getDrawable(context, expectedId);
        if (drawable == null || expectedDrawable == null) {
            return false;
        }
        if (drawable instanceof StateListDrawable && expectedDrawable instanceof StateListDrawable) {
            drawable = drawable.getCurrent();
            expectedDrawable = expectedDrawable.getCurrent();
        }
        if (drawable instanceof BitmapDrawable) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            Bitmap otherBitmap = ((BitmapDrawable) expectedDrawable).getBitmap();
            return bitmap.sameAs(otherBitmap);
        }
        return false;
    }

А вот мой эспрессо-тест:

@Test
    public void loginTextViewBackground() {
        onView(withId(R.id.loginTextView)).check(matches(withBackground(R.drawable.sign_in_login_bg)));
}

Но я получаю ошибку:

android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'has background resource 2131230909' doesn't match the selected view.
Expected: has background resource 2131230909
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@bcce82, 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)
at android.support.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:52)
at android.support.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:314)
at android.support.test.espresso.ViewInteraction.check(ViewInteraction.java:291)
at com.myproject.android.activity.SignInActivityTest.loginTextViewBackground(SignInActivityTest.java:158)

at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1879)
Caused by: junit.framework.AssertionFailedError: 'has background resource 2131230909' doesn't match the selected view.
Expected: has background resource 2131230909
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@bcce82, 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 android.support.test.espresso.matcher.ViewMatchers.assertThat(ViewMatchers.java:526)

Ответы [ 2 ]

0 голосов
/ 17 мая 2019

Это сработало для меня: HasBackgroundMatcher

onView(allOf(withId(R.id. loginTextView),
               hasBackground(R.drawable. sign_in_login_bg), isDisplayed()));
0 голосов
/ 12 июня 2018

Поскольку ваш рисованный объект является GradientDrawable, он должен обрабатываться и в вашем Matcher.Итак, ваш сопоставитель может выглядеть так:

private static boolean sameBitmap(Context context, Drawable drawable, int expectedId) {
    Drawable expectedDrawable = ContextCompat.getDrawable(context, expectedId);
    if (drawable == null || expectedDrawable == null) {
        return false;
    }

    if (drawable instanceof StateListDrawable && expectedDrawable instanceof StateListDrawable) {
        drawable = drawable.getCurrent();
        expectedDrawable = expectedDrawable.getCurrent();
    }
    if (drawable instanceof BitmapDrawable) {
        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
        Bitmap otherBitmap = ((BitmapDrawable) expectedDrawable).getBitmap();
        return bitmap.sameAs(otherBitmap);
    }

    if (drawable instanceof VectorDrawable ||
            drawable instanceof VectorDrawableCompat ||
            drawable instanceof GradientDrawable) {
        Rect drawableRect = drawable.getBounds();
        Bitmap bitmap = Bitmap.createBitmap(drawableRect.width(), drawableRect.height(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        Bitmap otherBitmap = Bitmap.createBitmap(drawableRect.width(), drawableRect.height(), Bitmap.Config.ARGB_8888);
        Canvas otherCanvas = new Canvas(otherBitmap);
        expectedDrawable.setBounds(0, 0, otherCanvas.getWidth(), otherCanvas.getHeight());
        expectedDrawable.draw(otherCanvas);
        return bitmap.sameAs(otherBitmap);
    }
    return false;
}
...