1package com.xtremelabs.robolectric.matchers;
2
3import android.widget.ImageView;
4import com.xtremelabs.robolectric.res.ResourceLoader;
5import org.hamcrest.Description;
6import org.hamcrest.Factory;
7import org.hamcrest.Matcher;
8import org.junit.internal.matchers.TypeSafeMatcher;
9
10import static com.xtremelabs.robolectric.Robolectric.shadowOf;
11
12public class ImageViewHasDrawableMatcher<T extends ImageView> extends TypeSafeMatcher<T> {
13    private int expectedResourceId;
14    private String message;
15
16    public ImageViewHasDrawableMatcher(int expectedResourceId) {
17        this.expectedResourceId = expectedResourceId;
18    }
19
20    @Override
21    public boolean matchesSafely(T actualImageView) {
22        if (actualImageView == null) {
23            return false;
24        }
25
26        ResourceLoader resourceLoader = ResourceLoader.getFrom(actualImageView.getContext());
27
28        int actualResourceId = shadowOf(actualImageView).getResourceId();
29        String actualName = nameOrUnset(resourceLoader, actualResourceId);
30        String expectedName = nameOrUnset(resourceLoader, expectedResourceId);
31        message = "[" + actualResourceId + " (" + actualName + ")] to equal [" + expectedResourceId + " (" + expectedName + ")]";
32        return actualResourceId == expectedResourceId;
33    }
34
35    private String nameOrUnset(ResourceLoader resourceLoader, int resourceId) {
36        return resourceId == 0 ? "unset" : resourceLoader.getNameForId(resourceId);
37    }
38
39
40    @Override
41    public void describeTo(Description description) {
42        description.appendText(message);
43    }
44
45    @Factory
46    public static <T extends ImageView> Matcher<T> hasDrawable(int expectedResourceId) {
47        return new ImageViewHasDrawableMatcher<T>(expectedResourceId);
48    }
49}
50