gpt4 book ai didi

android - 使用 “hasBackground” 进行 Espresso 测试

转载 作者:行者123 更新时间:2023-11-29 16:47:36 25 4
gpt4 key购买 nike

如何使用布局背景的颜色进行 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' doesn't match the selected view.

Expected: has background with drawable ID: -11141257

Got: "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}"

我如何比较这个?

最佳答案

我在 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 类,使其直接使用颜色而不是资源。

希望对您有所帮助!

关于android - 使用 “hasBackground” 进行 Espresso 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47417240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com