Robolectric测试从小部件启动的活动

时间:2014-09-21 21:04:21

标签: java android unit-testing robolectric

我是一个由图像和按钮组成的简单小部件,按钮应该启动一个活动。我试图编写一个Robolectric测试来测试单击按钮时是否启动了活动

我有两个问题,首先我在尝试点击按钮时获得了NPE:

java.lang.NullPointerException: can't get a shadow for null
   at org.robolectric.bytecode.ShadowWrangler.shadowOf(ShadowWrangler.java:415)
   at org.robolectric.Robolectric.shadowOf_(Robolectric.java:1020)
   at org.robolectric.Robolectric.shadowOf(Robolectric.java:671)
   at org.robolectric.shadows.ShadowIntent.fillIn(ShadowIntent.java:454)
   at android.content.Intent.fillIn(Intent.java)
   at org.robolectric.shadows.ShadowPendingIntent.send(ShadowPendingIntent.java:48)
   at android.app.PendingIntent.send(PendingIntent.java)
   at org.robolectric.shadows.ShadowRemoteViews$2$1.onClick(ShadowRemoteViews.java:61)
   at android.view.View.performClick(View.java:4084)

此外,我不确定如何获得通过按钮点击启动的活动的参考。

测试代码:

@Test
public void buttonShouldLaunchActivity() throws Exception {
    int widgetId = shadowAppWidgetManager.createWidget(HelloWidgetProvider.class, R.layout.hellowidget_layout);
    View helloWidgetView = shadowAppWidgetManager.getViewFor(widgetId);
    Button quickButton = (Button) helloWidgetView.findViewById(R.id.quick_add_button);
    quickButton.performClick();

    // Not sure how to get a handle of the activity started from a widget, this is what I have for an activity launched from another activity.
    Intent intent = Robolectric.shadowOf(activity).peekNextStartedActivity();
    assertEquals(QuickAddActivity.class.getCanonicalName(), intent.getComponent().getClassName());
}

任何想法都会被贬低,实际的小部件正在运行(活动已启动),但我只想对其进行测试。

1 个答案:

答案 0 :(得分:0)

peekNextStartedActivity()实际上是ShadowApplication上的一个方法。 ShadowContextWrapper上的方法(这是ShadowActivity隐式使用的)实际上只是一个调用shadow应用程序上的方法的包装器。

所以你应该能够做这样的事情,以获得你需要的东西:

Robolectric.getShadowApplication().peekNextStartedActivity()
相关问题