【发布时间】:2015-09-25 09:53:43
【问题描述】:
我希望能够将Espresso 监视Picasso 作为IdlingResource,以便在成功加载图像后我可以运行ViewMatchers。
通过浏览Picasso 源代码,我不明白为什么这不起作用。这是我尝试过的:
Picasso picasso = new Picasso.Builder(context).build();
Field dispatcherField = Picasso.class.getDeclaredField("dispatcher");
dispatcherField.setAccessible(true);
try {
Dispatcher dispatcher = (Dispatcher) dispatcherField.get(picasso);
Espresso.registerLooperAsIdlingResource(dispatcher.dispatcherThread.getLooper());
} catch (NoSuchFieldException e) {
throw new PicassoHasBeenRefactoredException();
} catch (Exception e) {
e.printStackTrace();
}
onView(withId(R.id.image_view)).check(matches(withImage(R.drawable.drawable)));
(是的,我知道,反射很恶心,但我找不到其他方法来处理Looper)
但是在尝试从ImageView获取Bitmap时会导致这个错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.drawable.BitmapDrawable.getBitmap()' on a null object reference
为了检查加载图像后测试是否按预期运行,我尝试引入Thread.sleep(1000) 代替IdlingResource 检查并通过了。
假设 IdlingResource 没有正确设置是否安全,更重要的是,在使用 Espresso 检查视图之前等待 Picasso 完成加载的正确方法是什么?
【问题讨论】:
-
你不能使用 Picasso 的 onSucess callback 来设置你的 IdelingResource 吗?
-
@RahulTiwari 我不想修改任何生产代码来适应测试,除非你的意思是别的?
-
我说的是使用 Picasso 提供的回调函数
onSuccess和onError并尽可能摆脱反射。所以是的,我说的是修改代码,但它肯定不会影响任何功能。 -
这是一个权衡。在我看来,在生产代码上设置一个 idlingResource 是非常无害的,并且会引导您获得更简单的测试代码。
标签: android picasso android-testing android-espresso