Java – Testing strategy for wrapper class

javajunittestingunit testing

In my Android project I decided to create wrapper around SharedPreferences(which is basically key-value storage) with following interface

interface Preferences{
    public void saveInt(int value, String key);
    public void saveString(String value, String key);
    public int readInt(String key);
    public String readString(String key);
}

Implemetation uses Android SharedPreferences API, simplified version looks like that:

public class SharedPrefencesWrapper implements Preferences{
    private SharedPreferences mSharedPreferences;

    public SharedPreferencesStorage(Context context) {
        mSharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }
    public void saveInt(int value, String key){
        mSharedPreferences.edit().putInt(key, value).commit();
    }
    //The same for all other public methods
}

Now I want to test SharedPreferencesWrapper class, every public method of Preferences class:

public class SharedPreferencesWrapperTest{
    @Test
    public void savesBoolean(){
       Preferences prefs = new SharedPreferencesWrapper(...);
       prefs.saveInt(3, "intKey");
       int savedValue = prefs.readInt("intKey");
       assertEquals(3, savedValue);
    }
}

Now, can the test look like that? Or should I use SharedPreferences API to check saved values in tests? My concern is that to retrieve the value I will use methods of SharedPrefencesWrapper, something doesn't feel right here.

Best Answer

In theory, you want to ensure the data has been stored using the SharedPreferences API, and so, in theory, you should check that the values stored using your wrapper are available when directly retrieved using the API.

In practice, especially if you intend that all your code should use your wrapper, you might as well only check it can retrieve what it stores, partly because one of the "normal" reasons for a wrapper is to allow for it to change the underlying storage mechanism, so in the future you might decide to store settings in a database, for example.

Related Topic