Reputation: 1506
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
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
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
Reputation: 2378
Intent intent = new Intent(ShadowApplication.getInstance().getApplicationContext(), Activity.class);
Upvotes: 1
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
Reputation: 2710
Try this
Intent intent = new Intent(Robolectric.getShadowApplication().getApplicationContext(),
MiAirlineActivity.class);
Upvotes: 9
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