我想写一个Espresso匹配器来验证'ImageView'是否有特定的位图集。由于该应用通过Glide进行图像加载,因此在考虑剪切/居中之前,我认为我必须在测试方面做同样的事情,然后才能实际比较预期位置和实际位图。与Glide同步加载图像
这里是我想出迄今:
BitmapRequestBuilder<Uri, Bitmap> bitmapRequest = Glide.with(imageView.getContext())
.load(Uri.parse("file:///android_asset/" + mPath))
.asBitmap();
switch (imageView.getScaleType()) {
case CENTER_CROP:
bitmapRequest.centerCrop();
break;
case FIT_CENTER:
case FIT_START:
case FIT_END:
bitmapRequest.fitCenter();
break;
default:
// no scaling applied to the ImageView under test
}
AtomicReference<Bitmap> bmRef = new AtomicReference<>();
bitmapRequest.into(new SimpleTarget<Bitmap>(
imageView.getMeasuredWidth(),
imageView.getMeasuredHeight()
) {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
bmRef.set(resource);
}
});
// ???
try {
Bitmap expected = bmRef.get();
return expected.sameAs(bitmap);
} catch (Exception e) {
throw new IllegalStateException("could not load asset " + mPath, e);
}
现在,这里的问题是,当然,我有一个僵局。我在主线程(匹配器在主线程IIRC上执行),Glide想要后端线程加载位图,然后在主线程(在onResourceReady中)本身返回。所以我需要从外部等待内部发布的结果,同时保持主线程运行。
我(未成功)试图通过Looper.loop()
// ???
推进目前的活套,并尝试了常规的锁定/等待方法,但没有任何工作。我没有想法...
这并不在这种情况下工作,遗憾的是,刚刚又试了一次。 –