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