How to use robolectric to test started intent with extra data

12,581

Solution 1

If you extract the generateRandomKey() method into a separate class you can then inject (either manually or using something like RoboGuice) a controlled version of that class into your test so that the 'random' key generated when Robolectric runs is actually a known value. But is still random in the production code.

You can then catch the intent your activity creates and test if 'key' contains the expected test value.


However, to answer your question directly...

When I'm testing if an intent was generated (in this case by a button click) and is pointing to the correct target I use

public static void assertButtonClickLaunchesActivity(Activity activity, Button btn, String targetActivityName) {
    btn.performClick();
    ShadowActivity shadowActivity = shadowOf(activity);
    Intent startedIntent = shadowActivity.getNextStartedActivity();
    ShadowIntent shadowIntent = shadowOf(startedIntent);
    assertThat(shadowIntent.getComponent().getClassName(), equalTo(targetActivityName));
}

Solution 2

Something like this?

Assert.assertTrue(UserActivity.class.equals(intent.getComponent().getClassName()));

or assertEquals?

Share:
12,581
Freewind
Author by

Freewind

A programmer ([email protected])

Updated on June 12, 2022

Comments

  • Freewind
    Freewind about 2 years

    In an activity, I started a new Intent with some random extra data:

    Intent newIntent = new Intent(this, UserActivity.class);
    newIntent.putExtra("key", generateRandomKey());
    startActivity(newIntent);
    

    I tested it like this:

    Intent intent = new Intent(myactivity, UserActivity.class);
    Assert.assertThat(activity, new StartedMatcher(intent));
    

    It's failed because the intent in my test code has not extra data key.

    Since the key is random, it's hard to provide a same key. So I just want to test if the target class of the intent is UserActivity, but found no way to do it.

    Is there a solution?

  • c4augustus
    c4augustus about 5 years
    This totally saved my day after trying Application.ActivityLifecycleCallbacks only to discover that Robolectric is not really starting the Activity.