Assert ImageView was loaded with specific drawable resource ID

狂风中的少年 提交于 2019-12-05 13:02:39

问题


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.


回答1:


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



回答2:


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



回答3:


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

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