我正在编写Robolectric单元测试,我需要断言ImageView有setImageResource(int)使用某个资源ID调用它。我正在使用fest-android进行断言但它似乎不包含此断言。
我还尝试从ImageView获取ShadowImageView用于ImageView,因为我知道它曾经让你访问它,但它现在已经消失了。
最后,我试图在我的代码中调用setImageDrawable而不是setImageResource,然后在我的测试断言中这样:
assertThat(imageView).hasDrawable(resources.getDrawable(R.drawable.some_drawable));
但这也失败了,即使失败消息清楚地表明它与正在加载的Drawable相同。
答案 0 :(得分:26)
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());
答案 1 :(得分:10)
来自Roboelectric 3.0 +
您可以这样做:
int drawableResId = Shadows.shadowOf(errorImageView.getDrawable()).getCreatedFromResId();
assertThat("error image drawable", R.drawable.ic_sentiment_dissatisfied_white_144dp, is(equalTo(drawableResId)));
答案 2 :(得分: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向你提交拉取请求。
答案 3 :(得分:0)
具有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))