robolectric 2 - create activity with intent

我怕爱的太早我们不能终老 提交于 2019-11-30 02:40:28

问题


Does creating an activity using the .withIntent() not work in Robolectric 2? I'm doing the following

    activity = Robolectric.buildActivity(MyActivity.class)
                            .create()
                            .withIntent(intent)
                            .get();

And i'm getting a NullPointerException when doing the following in the onCreate() of my activity.

Bundle bundle = getIntent().getExtras();

I can code a null check in my onCreate() and set the intent by doing the following but it seems redundant to set the intent and call the onCreate() method again when Robolectric already does that when creating the Activity instance. This seems like an unnecessary work around.

    Robolectric.shadowOf(activity).setIntent(intent);
    activity.onCreate(null);

回答1:


This is a case where a fluent-style API kinds of leads you down the wrong path...

You want to:

activity = Robolectric.buildActivity(MyActivity.class)
                        .withIntent(intent)
                        .create()
                        .get();

so that the intent is provided to the builder before it calls onCreate().




回答2:


For newer versions of Robolectric use Robolectric.buildActivity(Class, Intent).




回答3:


I figured out my problem. I wasn't instantiating the Intent properly. I was instantiating it with the no-arg constructor when i needed to give a Context and the class of the Activity it was being sent to




回答4:


EDIT: It was fixed in version 2.2.

I tackled with the same issue. It was reported but no fix has been provided yet. For now, I manage to hack it using Activity's setter before calling onCreate(), taking advantage from the fact that its lifecycle has not yet started:

Intent intent = new Intent();
MainActivity mainActivity = Robolectric.buildActivity(MainActivity.class)
                                       .create()
                                       .get();
mainActivity.setIntent(intent);
mainActivity.onCreate(null);



来源:https://stackoverflow.com/questions/17195761/robolectric-2-create-activity-with-intent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!