I'm writing a Robolectric unit test and I need to make an assertion that an ImageView had setImageResource(int) called on it with a certain resource ID. I'm using fest-android for assertions but it doesn't appear to contain this assertion.
I also tried to get the ShadowImageView from Robolectric for the ImageView because I know it used to give you access to this, but it's now gone.
Lastly, I tried to call setImageDrawable in my code instead of setImageResource, then in my test assert like this:
assertThat(imageView).hasDrawable(resources.getDrawable(R.drawable.some_drawable));
but this also fails, even though the failure message clearly shows it's the same Drawable being loaded.
For Background
ImageView imageView = (ImageView) activity.findViewById(R.id.imageview);
assertEquals(R.drawable.expected, Robolectric.shadowOf(imageView.getBackground()).getCreatedFromResId());
For Drawable
ImageView imageView = (ImageView) activity.findViewById(R.id.imageview);
assertEquals(R.drawable.expected, Robolectric.shadowOf(imageView.getDrawable()).getCreatedFromResId());
From Roboelectric 3.0+
This is how you can do:
int drawableResId = Shadows.shadowOf(errorImageView.getDrawable()).getCreatedFromResId();
assertThat("error image drawable", R.drawable.ic_sentiment_dissatisfied_white_144dp, is(equalTo(drawableResId)));
I ended up extending fest-android to solve this:
public class CustomImageViewAssert extends ImageViewAssert {
protected CustomImageViewAssert(ImageView actual) {
super(actual);
}
public CustomImageViewAssert hasDrawableWithId(int resId) {
boolean hasDrawable = hasDrawableResourceId(actual.getDrawable(), resId);
String errorMessage = String.format("Expected ImageView to have drawable with id <%d>", resId);
Assertions.assertThat(hasDrawable).overridingErrorMessage(errorMessage).isTrue();
return this;
}
private static boolean hasDrawableResourceId(Drawable drawable, int expectedResId) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
ShadowBitmap shadowBitmap = (ShadowBitmap) shadowOf(bitmap);
int loadedFromResourceId = shadowBitmap.getCreatedFromResId();
return expectedResId == loadedFromResourceId;
}
}
The magic sauce is:
ShadowBitmap shadowBitmap = (ShadowBitmap) shadowOf(bitmap);
int loadedFromResourceId = shadowBitmap.getCreatedFromResId();
which is Robolectric specific, so I can't submit a pull request to fest-android with this.
来源:https://stackoverflow.com/questions/18008044/assert-imageview-was-loaded-with-specific-drawable-resource-id