【发布时间】:2015-12-02 11:02:10
【问题描述】:
我有一个 ListView,其中包含通过自定义适配器创建的不同颜色的行,例如:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
convertView = mInflater.inflate(R.layout.row_unit, parent, false);
// ...
if( /* some condition */ ) {
convertView.setBackgroundColor(Color.LTGRAY);
} else {
convertView.setBackgroundColor(Color.WHITE);
}
return convertView;
}
在测试中,我想检查列表中的某个元素是否具有 Color LTGRAY。我创建了一个自定义匹配器:
public static Matcher<Object> backgroundShouldHaveColor(int expectedColor) {
return viewShouldHaveBackgroundColor(equalTo(expectedColor));
}
private static Matcher<Object> viewShouldHaveBackgroundColor(final Matcher<Integer> expectedObject) {
final int[] color = new int[1];
return new BoundedMatcher<Object, View>( View.class) {
@Override
public boolean matchesSafely(View view) {
color[0] =((ColorDrawable) view.getBackground()).getColor();
if( expectedObject.matches(color[0])) {
return true;
} else {
return false;
}
}
@Override
public void describeTo(final Description description) {
// Should be improved!
description.appendText("Color did not match " + color[0]);
}
};
}
尝试测试
onView(withText("itemtext")).check(matches(backgroundShouldHaveColor(Color.LTGRAY)));
我得到一个空指针异常。
【问题讨论】:
标签: java android-layout android-listview android-espresso matcher