0
我有通過自定義適配器等生成不同顏色的行一個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;
}
在測試中,我想檢查在列表中的某個元素是否具有顏色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)));
我得到一個空指針異常進行測試。