gpt4 book ai didi

Android-Espresso:使用 R.color.xxx 无法检查 textView 文本颜色

转载 作者:行者123 更新时间:2023-12-02 22:18:18 25 4
gpt4 key购买 nike

这是我的colors.xml

<color name="color_primary">#29c9b9</color>

这是我的 xml

<TextView
android:id="@+id/registerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/register"
android:textAllCaps="true"
android:textColor="@color/color_primary"/>

所以我想在 TextView 中编写 Espresso 测试检查 android:textColor="@color/color_primary"

这是我的测试:

    @Test
public void registerTextViewTextColor() {
onView(withId(R.id.registerTextView)).check(matches(withTextColor(Color.parseColor("#29c9b9"))));
}

这里匹配器:

public static Matcher<View> withTextColor(final int expectedId) {
return new BoundedMatcher<View, TextView>(TextView.class) {

@Override
protected boolean matchesSafely(TextView textView) {
return expectedId == textView.getCurrentTextColor();
}

@Override
public void describeTo(Description description) {
description.appendText("with text color: ");
description.appendValue(expectedId);
}
};
}

测试工作正常。

所以我更改测试以使用color_primary:

@Test
public void registerTextViewTextColor() {
onView(withId(R.id.registerTextView)).check(matches(withTextColor(R.color.color_primary)));}

但现在我收到错误:

android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with text color: <2131099686>' doesn't match the selected view.
Expected: with text color: <2131099686>
Got: "AppCompatTextView{id=2131296512, res-name=registerTextView, visibility=VISIBLE, width=180, height=53, 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@9e165b3, tag=null, root-is-layout-requested=false, has-input-connection=false, x=451.0, y=1508.0, text=Register, input-type=0, ime-target=false, has-links=false}"

最佳答案

如果您想从颜色资源中提取 int,您的 View 匹配器应如下所示:

public static Matcher<View> withTextColor(final int expectedId) {
return new BoundedMatcher<View, TextView>(TextView.class) {

@Override
protected boolean matchesSafely(TextView textView) {
int colorId = ContextCompat.getColor(textView.getContext(), expectedId);
return textView.getCurrentTextColor() == colorId;
}

@Override
public void describeTo(Description description) {
description.appendText("with text color: ");
description.appendValue(expectedId);
}
};
}

然后这应该会给出所需的结果:

onView(withId(R.id.registerTextView)).check(matches(withTextColor(R.color.color_primary)))

关于Android-Espresso:使用 R.color.xxx 无法检查 textView 文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50832573/

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