簡體   English   中英

Robolectric測試從小部件啟動的活動

[英]Robolectric Test an activity launched from a widget

我有一個簡單的小部件,其中包含一個圖像和一個按鈕,該按鈕應啟動一個活動。 我正在嘗試編寫一個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());
}

任何想法都會被理解,實際的小部件正在工作(活動已啟動),但我只是想對其進行測試。

peekNextStartedActivity()實際上是ShadowApplication上的方法。 ShadowContextWrapper上的方法(ShadowActivity隱式使用的方法)實際上只是一個包裝,在影子應用程序上調用該包裝。

因此,您應該能夠執行以下操作來獲得所需的內容:

Robolectric.getShadowApplication().peekNextStartedActivity()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM