unit testing - How to mock PreferenceManager in Android? -


i've written class using context, third party library , sharedpreferences preferencemanager.

it's possible mock context, third party library can mocked using mocking framework, preferencemanager?

i have 2 methods:

public void savestring(thirdpartyobject obj) {     sharedpreferences apppreferences =          preferencemanager.getdefaultsharedpreferences(mcontext);     sharedpreferences.editor editor = apppreferences.edit();     editor.putstring(mcontext.getstring(         r.string.preferences_string_name), obj.getstring());     editor.commit(); } 

and corresponding, loads preferences.

it doesn't want mock instance of preferencemanager (which used in preferencefragment or preferenceactivity).

you want either:

  1. a mock sharedpreferences, in case can mock context#getsharedpreferences (which called preferencemanager#getdefaultsharedpreferences anyhow). you'll have make mock sharedpreferences.editor if preferences edited, above. know how mock context, should straightforward.

  2. to use actual preferences in environment. easiest, , not bad idea. make it's cleaned tests don't interfere each other (or, depending on test environment, aren't affected manual use of app).

if do want mock preferencemanager instance (like in preferencefragment or preferenceactivity), can absolutely so.

since it's non-final, can generate mock preferencemanager , sharedpreferences using mockito (or mocking library) long have way provide code wherever ordinarily 1 (in non-test code, comes getpreferencemanager()).


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -