vikas
vikas

Reputation: 1506

robolectric 2 - create activity under test with intent

I am writing unit test with Robolectric. The setup looks like this

@RunWith(RobolectricTestRunner.class)
public class MiAirlineActivityTest {
    @Before
    public void setUpFor() {
        Intent intent = new Intent(HOW_TO_PASS_CONTEXT_HERE, MiAirlineActivity.class);
        intent.putExtra(EMPLOYEEID_EXTRA, "username");

        miAirlineActivity = Robolectric.buildActivity(MiAirlineActivity.class)
                                .withIntent(intent).start().get();
    }
}

How to pass the context while creating the new intent. I followed the example from this question.

There @David says,

"... i needed to give a Context and the class of the Activity it was being sent to"

How exactly I can do that ?

Note: Please don't mark it as duplicate of the above linked question. I am asking a new question since I could not add comment there.

Upvotes: 10

Views: 8817

Answers (6)

ChinLoong
ChinLoong

Reputation: 1833

I am posting this because when I google "android roboelectric 3 buildactivity intent", this page is top result.

testImplementation "org.robolectric:robolectric:3.7.1"

withIntent() is no longer available in robolectric 3.

I used the code below:

Intent intent = new Intent(HOW_TO_PASS_CONTEXT_HERE,MiAirlineActivity.class);
intent.putExtra(EMPLOYEEID_EXTRA, "username");
iAirlineActivity = Robolectric.buildActivity(MiAirlineActivity.class,intent).create().get();

Upvotes: 2

HunkD
HunkD

Reputation: 76

No need to create the context and target Activity class by using the constructor. Try this:

@Before
public void setUpFor() {
    Intent intent = new Intent();
    intent.putExtra(EMPLOYEEID_EXTRA, "username");

    miAirlineActivity = Robolectric.buildActivity(MiAirlineActivity.class)
                            .withIntent(intent).start().get();
}

Upvotes: 0

user3773337
user3773337

Reputation: 2378

Intent intent = new Intent(ShadowApplication.getInstance().getApplicationContext(), Activity.class);

Upvotes: 1

James Muranga
James Muranga

Reputation: 808

Build your activity with an intent

Intent intent = new Intent(HOW_TO_PASS_CONTEXT_HERE,MiAirlineActivity.class);
intent.putExtra(EMPLOYEEID_EXTRA, "username");
iAirlineActivity = Robolectric.buildActivity(MiAirlineActivity.class).withIntent(intent).create().get();

look at the roboelectric docs here

Upvotes: 2

Traxex1909
Traxex1909

Reputation: 2710

Try this

Intent intent = new Intent(Robolectric.getShadowApplication().getApplicationContext(),
                MiAirlineActivity.class);

Upvotes: 9

user2483079
user2483079

Reputation: 533

miAirlineActivity = Robolectric.buildActivity(MiAirlineActivity.class).create().get();
Intent intent = new Intent();
intent.putExtra(EMPLOYEEID_EXTRA, "username");
miAirlineActivity.setIntent(intent);
miAirlineActivity.onCreate(new Bundle());

This will launch your activity with the desired intent

Upvotes: 3

Related Questions