1 package com.xtremelabs.robolectric.matchers;
2 
3 import android.widget.ImageView;
4 import com.xtremelabs.robolectric.res.ResourceLoader;
5 import org.hamcrest.Description;
6 import org.hamcrest.Factory;
7 import org.hamcrest.Matcher;
8 import org.junit.internal.matchers.TypeSafeMatcher;
9 
10 import static com.xtremelabs.robolectric.Robolectric.shadowOf;
11 
12 public class ImageViewHasDrawableMatcher<T extends ImageView> extends TypeSafeMatcher<T> {
13     private int expectedResourceId;
14     private String message;
15 
ImageViewHasDrawableMatcher(int expectedResourceId)16     public ImageViewHasDrawableMatcher(int expectedResourceId) {
17         this.expectedResourceId = expectedResourceId;
18     }
19 
20     @Override
matchesSafely(T actualImageView)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 
nameOrUnset(ResourceLoader resourceLoader, int resourceId)35     private String nameOrUnset(ResourceLoader resourceLoader, int resourceId) {
36         return resourceId == 0 ? "unset" : resourceLoader.getNameForId(resourceId);
37     }
38 
39 
40     @Override
describeTo(Description description)41     public void describeTo(Description description) {
42         description.appendText(message);
43     }
44 
45     @Factory
hasDrawable(int expectedResourceId)46     public static <T extends ImageView> Matcher<T> hasDrawable(int expectedResourceId) {
47         return new ImageViewHasDrawableMatcher<T>(expectedResourceId);
48     }
49 }
50