我最终扩展了 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 提交拉取请求。