Skip to content
This repository has been archived by the owner on Mar 1, 2022. It is now read-only.

Cannot instantiate SecurePrefs in testing #21

Closed
IgorGanapolsky opened this issue Jul 15, 2015 · 5 comments
Closed

Cannot instantiate SecurePrefs in testing #21

IgorGanapolsky opened this issue Jul 15, 2015 · 5 comments

Comments

@IgorGanapolsky
Copy link

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?

@IgorGanapolsky IgorGanapolsky changed the title Cannot mock context Cannot instantiate SecurePrefs in testing Jul 15, 2015
@scottyab
Copy link
Owner

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
Copy link
Author

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
Copy link
Owner

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
Copy link

@IgorGanapolsky How did you solved this situation ?

@pedrodimoura
Copy link

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants