断言ImageView加载了特定的可绘制资源ID

Chr*_*rry 13 android unit-testing robolectric

我正在编写一个Robolectric单元测试,我需要断言ImageView 上有一个带有特定资源ID的setImageResource(int).我正在使用fest-android进行断言但它似乎不包含这个断言.

我还试图从ImageView 获取Robolectric 的ShadowImageView,因为我知道它曾经让你访问它,但它现在已经消失了.

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

assertThat(imageView).hasDrawable(resources.getDrawable(R.drawable.some_drawable));
Run Code Online (Sandbox Code Playgroud)

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

Man*_*uel 27

为背景

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

对于Drawable

ImageView imageView = (ImageView) activity.findViewById(R.id.imageview);
assertEquals(R.drawable.expected, Robolectric.shadowOf(imageView.getDrawable()).getCreatedFromResId());
Run Code Online (Sandbox Code Playgroud)

  • 在robolectric 2.4中,该方法是`getImageResourceId()` (2认同)

Pra*_*ash 13

来自Roboelectric 3.0+

这是你可以做的:

int drawableResId = Shadows.shadowOf(errorImageView.getDrawable()).getCreatedFromResId();
assertThat("error image drawable", R.drawable.ic_sentiment_dissatisfied_white_144dp, is(equalTo(drawableResId)));
Run Code Online (Sandbox Code Playgroud)


Chr*_*rry 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

神奇的酱油是:

ShadowBitmap shadowBitmap = (ShadowBitmap) shadowOf(bitmap);
int loadedFromResourceId = shadowBitmap.getCreatedFromResId();
Run Code Online (Sandbox Code Playgroud)

这是Robolectric特有的,所以我无法向fest-android提交拉取请求.