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:
a mock
sharedpreferences
, in case can mockcontext#getsharedpreferences
(which calledpreferencemanager#getdefaultsharedpreferences
anyhow). you'll have make mocksharedpreferences.editor
if preferences edited, above. know how mock context, should straightforward.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
Post a Comment