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?
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));
}