我正在测试的视图有动画,当我使用 Robolectric 进行测试时,它似乎出现了很大的错误。动画是一个简单的幻灯片,使用 Nineoldandroids 以实现兼容性。在 Robolectric 之外一切正常,但是我的单元测试因空指针而崩溃:
10:34:35.419 [DEBUG] [TestEventLogger] java.lang.NullPointerException
10:34:35.419 [DEBUG] [TestEventLogger] at com.nineoldandroids.view.animation.AnimatorProxy.applyTransformation(AnimatorProxy.java:316)
10:34:35.419 [DEBUG] [TestEventLogger] at android.view.animation.Animation.getTransformation(Animation.java:870)
10:34:35.420 [DEBUG] [TestEventLogger] at org.robolectric.shadows.ShadowView$2.run(ShadowView.java:492)
10:34:35.420 [DEBUG] [TestEventLogger] at org.robolectric.util.Scheduler.runOrQueueRunnable(Scheduler.java:218)
10:34:35.420 [DEBUG] [TestEventLogger] at org.robolectric.util.Scheduler.postDelayed(Scheduler.java:73)
10:34:35.421 [DEBUG] [TestEventLogger] at org.robolectric.shadows.ShadowChoreographer.postCallbackDelayed(ShadowChoreographer.java:44)
10:34:35.421 [DEBUG] [TestEventLogger] at android.view.Choreographer.postCallbackDelayed(Choreographer.java)
10:34:35.427 [DEBUG] [TestEventLogger] at org.robolectric.shadows.ShadowView.setAnimation(ShadowView.java:487)
10:34:35.429 [DEBUG] [TestEventLogger] at android.view.View.setAnimation(View.java)
10:34:35.431 [DEBUG] [TestEventLogger] at com.nineoldandroids.view.animation.AnimatorProxy.<init>(AnimatorProxy.java:66)
10:34:35.432 [DEBUG] [TestEventLogger] at com.nineoldandroids.view.animation.AnimatorProxy.wrap(AnimatorProxy.java:38)
10:34:35.432 [DEBUG] [TestEventLogger] at com.nineoldandroids.animation.PreHoneycombCompat$14.get(PreHoneycombCompat.java:161)
10:34:35.432 [DEBUG] [TestEventLogger] at com.nineoldandroids.animation.PreHoneycombCompat$14.get(PreHoneycombCompat.java:153)
10:34:35.432 [DEBUG] [TestEventLogger] at com.nineoldandroids.animation.PropertyValuesHolder.setupSetterAndGetter(PropertyValuesHolder.java:510)
10:34:35.433 [DEBUG] [TestEventLogger] at com.nineoldandroids.animation.ObjectAnimator.initAnimation(ObjectAnimator.java:410)
10:34:35.433 [DEBUG] [TestEventLogger] at com.nineoldandroids.animation.ValueAnimator.setCurrentPlayTime(ValueAnimator.java:538)
10:34:35.433 [DEBUG] [TestEventLogger] at com.nineoldandroids.animation.ValueAnimator.start(ValueAnimator.java:928)
10:34:35.433 [DEBUG] [TestEventLogger] at com.nineoldandroids.animation.ValueAnimator.start(ValueAnimator.java:951)
10:34:35.433 [DEBUG] [TestEventLogger] at com.nineoldandroids.animation.ObjectAnimator.start(ObjectAnimator.java:385)
10:34:35.433 [DEBUG] [TestEventLogger] at com.nineoldandroids.animation.AnimatorSet.start(AnimatorSet.java:502)
如果我在我的代码中添加一个检查以仅将 Nineoldandroids 用于 API <11,并且默认使用 android 本机动画,则测试通过就好了。从 Nineoldandroids 源我可以看到它在这一行上是空指针:
View view = mView.get();
mView 在哪里mView = new WeakReference<View>(view);
任何建议如何从测试用例而不是我的应用程序代码中理想地解决这个问题?