gpt4 book ai didi

java - Robolectric 测试从小部件启动的 Activity

转载 作者:行者123 更新时间:2023-11-30 02:39:37 25 4
gpt4 key购买 nike

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

我有两个问题,首先我在尝试单击按钮时收到 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)

此外,我不确定如何获取对通过单击按钮启动的 Activity 的引用。

测试代码:

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

如有任何想法,我们将不胜感激,实际的小部件正在运行( Activity 已启动),但我只想对其进行测试。

最佳答案

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

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

Robolectric.getShadowApplication().peekNextStartedActivity()

关于java - Robolectric 测试从小部件启动的 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25963852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com