Search code examples
androidunit-testingpreferencesandroid-preferences

Android: How can I Save, Clear, then Restore SharedPreferences for Unit Testing?


I know how to clear SharedPreferences to run my unit tests in a defined state like this: PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().clear().commit()

However, I'd like to be able to save and restore the settings I prefer as a user of my own application after I run my unit tests.

Is there an easy way to do this without manually saving and restoring each preference item individually?

Thanks, Jeff


Solution

  • It sounds like what you need to do is provide a wrapper around SharedPreferences which exposes your own shared preferences interface. E.g.

    public interface PreferencesProvider {
        String getStringValue(String key);
    }
    

    Whatever your class under test is (eg an Activity) can use a concrete implementation of PreferencesProvider which calls PreferenceManager.getDefaultSharedPreferences...etc. In your test class, you can substitute a fake concrete implementation to return whatever you like for your tests.

    This way your preferences provider is decoupled from your application class, and testing becomes simple. In fact, your tests never need touch the actual prefs stored on your phone.

    Putting this into action however requires some kind of dependency injection mechanism like RoboGuice.