Android:Espresso:如何检查MaterialButton的colorAccent(style.xml)?

时间:2019-04-04 11:14:05

标签: android android-espresso

在我的Android项目中,我编写了自定义匹配器以检查视图的背景颜色

 fun withBackgroundColorResId(expectedId: Int): Matcher<View> {

    return object : BoundedMatcher<View, ViewGroup>(ViewGroup::class.java) {
        override fun matchesSafely(view: ViewGroup): Boolean {
            val color = (view.background.current as ColorDrawable).color
            return color == ContextCompat.getColor(view.context, expectedId)
        }

        override fun describeTo(description: Description) {
            description.appendText("with background color: ")
            description.appendValue(context.getResources().getString(expectedId))
        }
    }
}

并使用:

      onView(withRecyclerView(R.id.tradersRecyclerView).atPositionOnView(CHECK_ITEM_LIST_POS, R.id.viewJsonButton))
            .check(matches(withBackgroundColorResId(R.color.colorPrimary)))

很好。

在colors.xml中

<color name="colorPrimary">@color/mcgpalette0_500</color>
    <color name="colorPrimaryDark">@color/mcgpalette0_700</color>
    <color name="colorAccent">@color/colorPrimary</color>

但是我在xml中添加了新按钮

            <com.google.android.material.button.MaterialButton
                android:id="@+id/viewJsonButton"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="@dimen/half_default_margin"
                android:layout_marginEnd="@dimen/half_default_margin"
                android:layout_marginBottom="@dimen/half_default_margin"
                android:onClick="@{() -> handler.onClickViewJson(item)}"
                android:text="@string/view_json"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:textAllCaps="true" />

此按钮的背景色等于colorAccent中的style.xml

  <item name="colorAccent">@color/colorAccent</item>

现在,当我检查此按钮的背景色时,我的自定义匹配器将返回FALSE:

    androidx.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with background color: "#ff565656"' doesn't match the selected view.
Expected: with background color: "#ff565656"
Got: "MaterialButton{id=2131231029, res-name=viewJsonButton, visibility=VISIBLE, width=349, height=144, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, layout-params=androidx.constraintlayout.widget.ConstraintLayout$LayoutParams@245846d, tag=null, root-is-layout-requested=false, has-input-connection=false, x=707.0, y=60.0, text=View Json, input-type=0, ime-target=false, has-links=false}"

at dalvik.system.VMStack.getThreadStackTrace(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:580)

0 个答案:

没有答案