This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Q: How do I provide test data for Robolectric SharedPreferences?

I started out with Robolectric pretty well elsewhere, but I ran into a few hurdles with SharedPreferences.

I have two test cases

1, the activity requires a new/empty sharedPreferences

2. The activity expects that there is already some data in sharedPreferences

For test case 1, the tests passed as expected, so everything was fine

However, for test case 2, I can’t seem to find a good way to provide some fake data to Robolectric, so the Activity can’t access it.

It feels like a very common use, but I can’t seem to figure out what to do!

Answer 1:

All you need to do is grab sharedPreferences and populate it with the data you need.

SharedPreferences sharedPreferences = ShadowPreferenceManager.getDefaultSharedPreferences(Robolectric.application.getApplicationContext());
sharedPreferences.edit().putString("testId"."12345").commit();
Copy the code

If you have a custom SharedPreferences, you should be able to do this (it hasn’t been properly tested, but it will work)

SharedPreferences sharedPreferences = Robolectric.application.getSharedPreferences("you_custom_pref_name", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("testId"."12345").commit();
Copy the code

Answer 2:

If you’re using Robolectric 3, things change slightly

 SharedPreferences sharedPreferences =
     RuntimeEnvironment.application.getSharedPreferences(
         "you_custom_pref_name", Context.MODE_PRIVATE);
Copy the code

You can then add preferences as usual

 sharedPreferences.edit().putBoolean(
    activity.getString(R.string.pref_somepref), true).commit();
Copy the code

Answer 3:

For my Robolectric 3.1 SNAPSHOT solution… It may be useful to you


Context context = RuntimeEnvironment.application.getApplicationContext();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
sharedPreferences.edit().putBoolean("useOnlyOnWifi".false).commit();
Copy the code

This article translation to Stack Overflow: stackoverflow.com/questions/9…