Blog about nerd stuff, programming and related tools

Espresso compare color values

Published / by glethien / Leave a Comment

I’ve started to write automated UI tests using Espresso. This comes in handy, as you can run them after each commit to the master branch. This can be done using Jenkins.

There are a lot of default matchers but for one case I need to check, I was missing a matcher for the background color of a linear layout. I needed to check if the player has too few gold coins that he can’t buy items in the shop, but on the other hand the items should be displayed anyway. I’ve checked that the layout is not clickable but I wanted to make sure that the the user has a visible notificataion. Therefore I switched a green LinearLayout to a grey background. Now to check this using Espresso I needed a custom matcher which compares the background color of the LinearLayout with the provided color. Here is what the matcher looks like.

public static Matcher<View> withBgColor(final int color) {


    return new BoundedMatcher<View, LinearLayout>(LinearLayout.class) {
        public boolean matchesSafely(LinearLayout layout) {
            return color == ((ColorDrawable) layout.getBackground()).getColor();

        public void describeTo(Description description) {
            description.appendText("With background color: ");


This is pretty simple. Just write a static method returning the Matcher<View> In addition check that the color you’ve inserted is not null. Override the two methods of the BoundedMatcher. The first one is the actual comparison/test and the 2nd one appends a short error message if the test fails. No magic!

And this is how you can use the matcher in your test

.check(matches(withBgColor(ContextCompat.getColor(getInstrumentation().getTargetContext(), R.color.grey_300))));

If you ever need such a test, feel free to use this code.

Leave a Reply

Your email address will not be published. Required fields are marked *