Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

robolectric 2 - create activity with intent

Tags:

robolectric

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);
like image 992
David Avatar asked Jun 19 '13 15:06

David


3 Answers

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().

like image 172
Andy Dennie Avatar answered Oct 17 '22 08:10

Andy Dennie


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

like image 30
CorayThan Avatar answered Oct 17 '22 07:10

CorayThan


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

like image 38
David Avatar answered Oct 17 '22 09:10

David