我一直在用 Robolectric 进行测试,一切都很棒。然后我在我的应用程序类中实现了 Google Analytics,测试开始失败。当我在测试期间膨胀视图时,似乎发生了失败。这是堆栈跟踪:
java.lang.NullPointerException: null
at com.google.analytics.tracking.android.AnalyticsGmsCoreClient$AnalyticsServiceConnection.onServiceConnected(AnalyticsGmsCoreClient.java:176)
at org.robolectric.shadows.ShadowApplication$2.run(ShadowApplication.java:209)
at org.robolectric.util.Scheduler$PostedRunnable.run(Scheduler.java:162)
at org.robolectric.util.Scheduler.runOneTask(Scheduler.java:107)
at org.robolectric.util.Scheduler.advanceTo(Scheduler.java:92)
at org.robolectric.util.Scheduler.advanceToLastPostedRunnable(Scheduler.java:68)
at org.robolectric.util.Scheduler.unPause(Scheduler.java:25)
at org.robolectric.shadows.ShadowLooper.unPause(ShadowLooper.java:219)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:258)
at org.robolectric.shadows.ShadowViewGroup.addView(ShadowViewGroup.java:32)
at android.view.ViewGroup.addView(ViewGroup.java)
at android.view.ViewGroup.addView(ViewGroup.java:3225)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:750)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at org.robolectric.shadows.ShadowView.inflate(ShadowView.java:82)
at android.view.View.inflate(View.java)
这是我的 BaseActivity 的 Robolectric 代码:
@RunWith(RobolectricTestRunner.class)
public class BaseActivityTest {
ActivityController<TestActivity> activityController;
TestActivity activity;
@Before
public void setUp(){
activityController = Robolectric.buildActivity(TestActivity.class).create().start();
}
@After
public void takeDown(){
activityController.stop().destroy();
activity = null;
}
@Test
public void testOnPauseState(){
activity = activityController.resume().pause().get();
assertFalse(activity.getBus().isActive());
}
}
按照Google Analytics 示例,我的 Application 类实现了 Google Analytics。每当我使用我的应用程序运行测试时,就会发生中断。我试过实现 Robolectric 的 MockApplication 对象,但没有改变;我必须从我的 Application 对象中删除 Google Analytics 才能让它工作。有没有人有任何解决方案可以让我使用 Google Analytics 运行 Robolectric?