Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use robolectric to test started intent with extra data

Tags:

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?

like image 583
Freewind Avatar asked Sep 20 '12 08:09

Freewind


People also ask

Is Robolectric deprecated?

Robolectric is intended to be fully compatible with Android's official testing libraries since version 4.0. As such we encourage you to try these new APIs and provide feedback. At some point the Robolectric equivalents will be deprecated and removed.

How Robolectric works?

Robolectric works by creating a runtime environment that includes the real Android framework code. This means when your tests or code under test calls into the Android framework you get a more realistic experience as for the most part the same code is executed as would be on a real device.

What is the significance of Robolectric?

Robolectric provides a JVM compile version of the android. jar file. Robolectric handles views, resource loading, and many other things that are implemented in the Android native. This enables you to run your Android tests in your development environment, without requiring any other setup to run the test.


1 Answers

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)); } 
like image 74
Paul D'Ambra Avatar answered Sep 18 '22 12:09

Paul D'Ambra