Changing SharedPreferences of a Context instance for testing with Robolectric

The following code will get it done in a snap

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

Explanation

 

You use “RuntimeEnvironment.application.getApplicationContext();” to create an instance of a Context object.

You return the preferences, and modify the needed value and then commit it.

The next time this instance of Context returns SharedPreferences, it will return the version that you modified.

Change as many settings as you need to, then pass the context to the method you are trying to test!

 

Leave a Reply

Your email address will not be published. Required fields are marked *