正确测试Glide Image Loader实施

时间:2019-03-27 19:39:34

标签: android unit-testing android-glide robolectric

我在Android中创建了ImageDownloader界面。一种实现方式是使用Glide库,该库在其中基于URL下载位图图像,并在位图可用时调用回调。

GlideImageDownloader.java

public class GlideImageDownloader implements IImageDownloader {

    private static final String TAG = GlideImageDownloader.class.getSimpleName();

    private RequestManager mRequestManager;

    public GlideImageDownloader(Context context) {
        mRequestManager = Glide.with(context);
    }

    @Override
    public void downloadImage(String sourceUrl, DownloadImageCallback callback) {

        BitmapSimpleTarget target = new BitmapSimpleTarget(callback);

        mRequestManager
                    .load(sourceUrl)
                    .asBitmap()
                    .listener(target)
                    .into(target);
    }

    /**
     * BitmapSimple target that provides a Bitmap to the callback.  Glide manages a cache and download retries.
     */
    static class BitmapSimpleTarget extends SimpleTarget<Bitmap> implements RequestListener<String, Bitmap> {

        private DownloadImageCallback mCallback;

        BitmapSimpleTarget(@NonNull DownloadImageCallback callback) {
            super();
            this.mCallback = callback;
        }

        @Override
        public boolean onException(Exception e, String s, Target<Bitmap> target, boolean b) {
            Log.d(TAG, String.format(Locale.ROOT, "onException(%s, %s)", e, target), e);
            return false;
        }

        @Override
        public boolean onResourceReady(Bitmap bitmap, String s, Target<Bitmap> target, boolean b, boolean b1) {
            Log.i(TAG, String.format(Locale.ROOT, "onResourceReady (%s)", target));
            return false;
        }

        @Override
        public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
            mCallback.onBitmapReady(bitmap);
        }
    }
}

运行该应用程序效果很好。但是,当我尝试为其创建单个单元测试时,它似乎触发了一个新线程,但从未调用回调。

我想知道是否需要伪造的网络层,或者是否需要调用任何函数来恢复任何异步调用(因为我知道Glide可以异步工作)。

GlideImageDownloaderTest.java

@Before
public void setup() {
    Context context = ApplicationProvider.getApplicationContext();
    glideImageDownloader = new GlideImageDownloader(context);
}

@Test
public void testDownloadImage_RegularCase() {
    CountDownLatch latch = new CountDownLatch(1);

    IImageDownloader.DownloadImageCallback callback = new IImageDownloader.DownloadImageCallback() {
        @Override
        public void onBitmapReady(Bitmap bitmap) {
            assertNotNull(bitmap);
            latch.countDown();
        }
    };

    GlideImageDownloader.BitmapSimpleTarget target = new GlideImageDownloader.BitmapSimpleTarget(callback);
    glideImageDownloader.downloadImage(URL, callback);

    latch.await();
}

我如何正确测试此GlideImageDownloader实现?

0 个答案:

没有答案