带有“hasBackground”的浓缩咖啡测试
Posted
技术标签:
【中文标题】带有“hasBackground”的浓缩咖啡测试【英文标题】:Espresso test with “hasBackground” 【发布时间】:2018-05-05 03:52:12 【问题描述】:如何使用布局背景的颜色进行 espresso 测试?目前使用hasBackground():
onView(withId(R.id.backgroundColor)).check(matches(hasBackground(Color.parseColor("#FF55ff77"))));
但是出现错误:
android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'has background with drawable ID: -11141257' 与所选视图不匹配。
预期:具有可绘制 ID 的背景:-11141257
得到:“LinearLayoutid=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"
如何比较?
【问题讨论】:
【参考方案1】:我在 Hamcrest lib 的帮助下使用自定义匹配器:
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
类,使其直接使用颜色而不是资源。
希望对你有帮助!
【讨论】:
材质按钮的背景色调如何验证?因为在那种情况下,背景总是空的【参考方案2】:另一种方法是直接从视图中检索颜色值:
val bar = activityRule.activity.findViewById<View>(R.id.backgroundColor)
val actualColor = (bar.background as ColorDrawable).color
val expectedColor = Color.parseColor("#FF55ff77")
assertEquals(actualColor, expectedColor)
【讨论】:
以上是关于带有“hasBackground”的浓缩咖啡测试的主要内容,如果未能解决你的问题,请参考以下文章