18

我正在编写一个Robolectric单元测试,我需要断言 ImageView 已使用某个资源 ID 在其上调用了setImageResource(int) 。我正在使用fest-android进行断言,但它似乎不包含此断言。

我还尝试从 Robolectric 为 ImageView 获取ShadowImageView,因为我知道它曾经让您可以访问它,但现在它已经消失了。

最后,我尝试在我的代码中调用 setImageDrawable 而不是 setImageResource,然后在我的测试断言中像这样:

assertThat(imageView).hasDrawable(resources.getDrawable(R.drawable.some_drawable));

但这也失败了,即使失败消息清楚地表明它是相同的 Drawable 正在加载。

4

4 回答 4

34

背景

ImageView imageView = (ImageView) activity.findViewById(R.id.imageview);
assertEquals(R.drawable.expected, Robolectric.shadowOf(imageView.getBackground()).getCreatedFromResId());

对于可绘制

ImageView imageView = (ImageView) activity.findViewById(R.id.imageview);
assertEquals(R.drawable.expected, Robolectric.shadowOf(imageView.getDrawable()).getCreatedFromResId());
于 2014-03-10T08:37:14.863 回答
20

从 Roboelectric 3.0+

您可以这样做:

int drawableResId = Shadows.shadowOf(errorImageView.getDrawable()).getCreatedFromResId();
assertThat("error image drawable", R.drawable.ic_sentiment_dissatisfied_white_144dp, is(equalTo(drawableResId)));
于 2016-09-22T18:03:26.130 回答
6

我最终扩展了 fest-android 来解决这个问题:

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

神奇的酱汁是:

ShadowBitmap shadowBitmap = (ShadowBitmap) shadowOf(bitmap);
int loadedFromResourceId = shadowBitmap.getCreatedFromResId();

这是 Robolectric 特有的,所以我不能用这个向 fest-android 提交拉取请求。

于 2013-08-02T04:47:42.913 回答
1

使用 kotlin 扩展:

fun ImageView.hasDrawable(resId: Int): Boolean =
    Shadows.shadowOf(this.drawable).createdFromResId == resId

fun ImageView.hasBackground(resId: Int): Boolean =
    Shadows.shadowOf(this.background).createdFromResId == resId

用法:

assertTrue(image.hasDrawable(R.drawable.image_resource))
于 2020-09-24T05:54:48.180 回答