Assert ImageView was loaded with specific drawable resource ID

喜欢而已 提交于 2019-12-04 02:10:32
Manuel

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());
Prakash

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!