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))); 

我得到一个空指针异常进行测试。

回答

1

下,似乎为我工作:

onView(withChild(withText("itemtext"))) // this matches the LinearLayout or row/convertview 
     .check(matches(withBgColor(Color.LTGRAY))); 

下,定制匹配是:

public static Matcher<View> withBgColor(final int color) { 
    Checks.checkNotNull(color); 
    return new BoundedMatcher<View, LinearLayout>(LinearLayout.class) { 
     @Override 
     public boolean matchesSafely(LinearLayout row) { 
      return color == ((ColorDrawable) row.getBackground()).getColor(); 
     } 
     @Override 
     public void describeTo(Description description) { 
      description.appendText("with text color: "); 
     } 
    }; 
} 

这是一个三分栏列表视图,其中每一行由一个LinearLayout中的3个孩子TextViews 。 “withText(”itemtext“)”匹配第一列中的元素/ TextView。此列中的元素是唯一的。