简体   繁体   English

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

[英]Robolectric Test an activity launched from a widget

I've a simple widget which consists of an image and a button, the button should launch an activity. 我有一个简单的小部件,其中包含一个图像和一个按钮,该按钮应启动一个活动。 I'm trying to write a Robolectric test to test that the activity is launched when the button is clicked 我正在尝试编写一个Robolectric测试,以测试单击该按钮时是否启动了活动

I've two problems, firstly I'm getting an NPE when attempting to click the button: 我有两个问题,首先是我在尝试单击按钮时遇到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)

Also I'm not sure how to get a reference to the activity launched via the button click. 另外,我不确定如何获得对通过单击按钮启动的活动的引用。

Code for test: 测试代码:

@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());
}

Any thoughts would be apreciated, the actual widget is working (the activity is launched) but I'd just like to have a test for it. 任何想法都会被理解,实际的小部件正在工作(活动已启动),但我只是想对其进行测试。

peekNextStartedActivity() is actually a method on the ShadowApplication. peekNextStartedActivity()实际上是ShadowApplication上的方法。 The method on ShadowContextWrapper (which is what the ShadowActivity implicitly uses) is actually just a wrapper that calls the one on the shadow application. ShadowContextWrapper上的方法(ShadowActivity隐式使用的方法)实际上只是一个包装,在影子应用程序上调用该包装。

So you should be able to do something like this, to get what you need: 因此,您应该能够执行以下操作来获得所需的内容:

Robolectric.getShadowApplication().peekNextStartedActivity()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM