开发者

how do I get current activity with Robolectric?

开发者 https://www.devze.com 2023-04-01 20:42 出处:网络
Suppose I have an activity A that launches another activity B from within its onCreate() method, expecting for results.

Suppose I have an activity A that launches another activity B from within its onCreate() method, expecting for results.

开发者_如何学编程

How do I get activity B using Robolectric?


How about this:

ActivityA activityA = setupActivity(ActivityA.class);
// Start other activity by e.g. pushing on a button
Intent intentForB = shadowOf(activityA).peekNextStartedActivity();
ActivityB activityB = buildActivity(ActivityB.class).withIntent(intentForB)
    .create().get();


maybe you could verify that the activity that the button launched is as expected?

    button.performClick();
    assertThat(activity, new StartedMatcher( SecondActivity.class));


From the Roboletric documentation:

[...], Robolectric is only able to validate that the second activity would have been launched, but not that it is actually launched.

So you cannot get the Activity in itself, but you can intercept the Intent being passed and check if the right activity would have been launched.

For that you can use Shadows. Here is the code to check if ActivityB is launched during ActivityA's onCreate method (note: I am using Kotlin but the Java code looks pretty much the same).

// The activity should be built using Roboletric's method
val activityA = Robolectric.buildActivity(ActivityA::class.java)
            .setup() // setup calls onCreate and onResume
            .get()

// now we need a Shadow (spooky!) to verify the next activity is started
val shadowOfA = Shadows.shadowOf(activityA)

// with the shadow it is easy if ActivityB was launched
assertThat(shadowOfA.getNextStartedActivity().getComponent())
            .isEqualTo(ComponentName(activityA, ActivityB::class.java))

The getNextStartedActivity method from ShadowActivity returns the intent being started. You can check its components to see if it matches what you want and even check inside the Bundle to see if you are passing everything you need.

Documentation for getNextStartedActivity: http://robolectric.org/javadoc/3.0/org/robolectric/shadows/ShadowContextWrapper.html#getNextStartedActivity--

0

精彩评论

暂无评论...
验证码 换一张
取 消