在Espresso测试中使用“hasBackground”

3

如何使用布局背景的颜色来进行espresso测试?目前可以使用hasBackground()方法:

onView(withId(R.id.backgroundColor)).check(matches(hasBackground(Color.parseColor("#FF55ff77"))));

但是出现了错误:
android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: '具有drawable ID:-11141257的背景'与所选视图不匹配。
预期结果:具有drawable ID:-11141257的背景。
得到的结果:"LinearLayout {id = 2130968576,res-name = backgroundColor,visibility = VISIBLE,width = 996,height = 1088,has-focus = false,has-focusable = false,has-window-focus = true,is-clickable = false,is-enabled = true,is-focused = false,is-focusable = false,is-layout-requested = false,is-selected = false,layout-params = android.widget.LinearLayout $ LayoutParams @ e55f6e7,tag = null,root-is-layout-requested = false,has-input-connection = false,x = 42.0,y = 601.0,child-count = 2} "。
我该如何比较这个?
2个回答

3
我正在使用自定义匹配器和 Hamcrest 库来完成它:

Hamcrest 是一个帮助你编写自定义匹配器的库。

public class BackgroundColourMatcher extends TypeSafeMatcher<View> {

    @ColorRes
    private final int mExpectedColourResId;

    private int mColorFromView;

    public BackgroundColourMatcher(@ColorRes int expectedColourResId) {
        super(View.class);
        mExpectedColourResId = expectedColourResId;
    }

    @Override
    protected boolean matchesSafely(View item) {

        if (item.getBackground() == null) {
            return false;
        }
        Resources resources = item.getContext().getResources();
        int colourFromResources = ResourcesCompat.getColor(resources, mExpectedColourResId, null);
        mColorFromView = ((ColorDrawable) item.getBackground()).getColor();
        return mColorFromView == colourFromResources;
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("Color did not match " + mExpectedColourResId + " was " + mColorFromView);
    }
}

您可以为您的匹配器提供以下类似内容:

public class CustomTestMatchers {

    public static Matcher<View> withBackgroundColour(@ColorRes int expectedColor) {
        return new BackgroundColourMatcher(expectedColor);
    }
}

最后在您的测试中:
onView(withId(R.id.my_view)).check(matches(withBackgroundColour(R.color.color_to_check)))

您可以轻松修改BackgroundColourMatcher类,使其直接使用颜色而不是资源。

希望对您有所帮助!


如何验证材料按钮的背景色调?因为在这种情况下,背景将始终为空。 - Jimit Patel

1

另一种方法是直接从视图中检索颜色值:

val bar = activityRule.activity.findViewById<View>(R.id.backgroundColor)
val actualColor = (bar.background as ColorDrawable).color
val expectedColor = Color.parseColor("#FF55ff77")
assertEquals(actualColor, expectedColor)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接