Android: how can I save, clean, and then restore the general settings for unit testing?

I know how to clear SharedPreferences to run my unit tests in a certain state as follows: PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().clear().commit()

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

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

Thanks Jeff

+4
source share
1 answer

It looks like you need to wrap around SharedPreferences, which provides your own general settings interface. For instance.

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

Regardless of your class being tested (e.g. Activity), you can use a specific implementation of PreferencesProvider that calls PreferenceManager.getDefaultSharedPreferences ... etc. In your test class, you can replace a fake specific implementation to return whatever you like for your tests.

Thus, your preference provider is separate from your application class, and testing becomes simple. In fact, your tests never require touching the actual prefs stored on your phone.

Putting this into action, however, requires some kind of dependency injection mechanism, such as RoboGuice.

+2
source

Source: https://habr.com/ru/post/1332966/


All Articles