2014-09-21 51 views
1

我有一个简单的小部件,它包含一个图像和一个按钮,该按钮应该启动一个活动。我试图写一个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()); 
} 

任何想法,将apreciated,实际的小部件在工作(活动启动),但我只是想有一个测试它。

+0

你这个随时随地? – Jodes 2014-09-27 08:17:26

+0

不幸的是,如果我这样做,我会更新... – Bacon 2014-09-28 20:14:12

回答

0

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

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

Robolectric.getShadowApplication().peekNextStartedActivity()