scottyab / secure-preferences

Android Shared preference wrapper than encrypts the values of Shared Preferences. It's not bullet proof security but rather a quick win for incrementally making your android app more secure.
1.53k stars 235 forks source link

Cannot instantiate SecurePrefs in testing #21

Closed IgorGanapolsky closed 9 years ago

IgorGanapolsky commented 9 years ago

Hi I am trying to write unit tests, one of which requires an instance of SecurePreferences. So I am passing a context like this: mContext = Mockito.mock(Context.class); securePreferences = new SecurePreferences(mContext);

However, the context isn't mocked, and as a result I cannot use SecurePrefs in testing. Do you have any ideas about this?

scottyab commented 9 years ago

I've not used Mockito, can you test the standard Shared Preferences ok? if so could you paste a code sample or link to example. thx

IgorGanapolsky commented 9 years ago

The error actually happens because I am running my unit tests on the JVM, and hence don't access to a Context (which SecurePreferences requires).

scottyab commented 9 years ago

Ok, understood. But my question still stands if you can show me a test with config working using the standard Shared Preferences then I can see about getting securePreferences working. However if you cannot test standard Shared Preferences then this is not something this library is going to be able to solve.

danilodequeiroz commented 6 years ago

@IgorGanapolsky How did you solved this situation ?

pedrodimoura commented 5 years ago

I am facing the same problem. Its really weird!

val sp = SecurePreferences(context, context.packageName, PREFS)

I can test SharedPreferences normally but, when I try to get an instance of SecurePreferences with a mocked context throws an NullPointerException in line 85 because its a mocked context and the getDeviceSerialNumber cannot get an instance of ContextResolver in this method:

private static String getDeviceSerialNumber(Context context) {
        try {
            String deviceSerial = (String)Build.class.getField("SERIAL").get((Object)null);
            return TextUtils.isEmpty(deviceSerial) ? Secure.getString(context.getContentResolver(), "android_id") : deviceSerial;
        } catch (Exception var2) {
            return Secure.getString(context.getContentResolver(), "android_id");
        }
    }

I don't know if I am doing something wrong, but, my tests are not passing because of this problem and I am close to delete this library of my project because of that.