Testing background color espresso Android


Is it possible to check if the background color matches a given color with espresso?


I made a custom matcher, similar to what @Irfan suggested, thanks!

public static Matcher<Object> backgroundShouldHaveColor(int expectedColor) {
    return buttondShouldHaveBackgroundColor(equalTo(expectedColor));
private static Matcher<Object> buttonShouldHaveBackgroundColor(final Matcher<Integer> expectedObject) {
    final int[] color  new int[1];
    return new BoundedMatcher<Object, Button>( Button.class) {
        public boolean matchesSafely(final Button actualObject) {

            color[0] ((ColorDrawable) actualObject.getBackground()).getColor();

            if( expectedObject.matches(color[0])) {
                return true;
            } else {
                return false;
        public void describeTo(final Description description) {
            // Should be improved!
            description.appendText("Color did not match "+color[0]);


I am not sure about that but we can retrieve the color of some of elements like button and text views `

Button button  (Button) findViewById(R.id.my_button);
Drawable buttonBackground  button.getBackground();

and you can try like this

ColorDrawable b_color  (ColorDrawable) button.getBackground();

and then

int color  b_color.getColor();
if (color  R.color.green) {
    log("color is green");

Hope this will get you started.

Answered By – Irfan

Leave a Comment