In our Espresso tests, we need to customize the launch intent to pass custom extras and so on. Therefore, we set the launchActivity
flag to false
:
@Rule
public final ActivityTestRule<CreateQuoteActivity> mActivityRule = new ActivityTestRule<>(
CreateQuoteActivity.class, true, false
);
Now, I want to get a reference to the activity under test. If that flag was true
, I would use mActivityRule.getActivity()
. However, now mActivityRule.getActivity()
returns null
.
How can I get a reference to the activity?
If you have set that launchActivity
to false
, you only have access to the activity when you actually go ahead and launch it.
So, your activity context is right there:
final CreateQuoteActivity activity = mActivityRule.launchActivity(mIntent);
With the ActivityTestRule
you can configure an Intent for each test.
@Test
public void myTest() {
Intent intent = new Intent();
intent.putExtra(TAG_EXTRA, XXX);
mActivityRule.launchActivity(intent);
//......
}
If the intent is the same for all tests you can set it in the @Before
method.
@Before
public void setUp() {
Intent intent = new Intent();
intent.putExtra(TAG_EXTRA, XXX);
mActivityRule.launchActivity(intent);
}
If you launch an activity and then launch a second one after this you can use the method that has been posted here that gets the currently resumed activity instance.
The basic code in question is as follows.
public static Activity getActivityInstance() {
getInstrumentation().runOnMainSync(new Runnable() {
public void run() {
Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance()
.getActivitiesInStage(RESUMED);
if (resumedActivities.iterator().hasNext()) {
resumedActivity = (Activity) resumedActivities.iterator().next();
}
}
});
return resumedActivity;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.