Android junit - access custom shared preferences in ServiceTestCase

966 views Asked by At

I want to get shared preferences in ServiceTestCase:

SharedPreferences preferences = context.getSharedPreferences("preferences_name", Context.MODE_PRIVATE);

and do something like that:

int value = preferences.getInt("key", 0);
preferences.edit().putInt("key", ++value).commit();
int newValue = preferences.getInt("key", 0);
assertTrue(value != newValue);

However, this does not work. Test simply fails.

I've tried with different contexts:

getContext();

and

getSystemContext();

and also

getContext().createPackageContext(this.getClass().getPackage().getName(), Context.CONTEXT_IGNORE_SECURITY);

and finally

getSystemContext().createPackageContext(this.getClass().getPackage().getName(), Context.CONTEXT_IGNORE_SECURITY);

Am I doing something wrong?

Or maybe it's impossible to get custom shared preferences file in ServiceTestCase?

What about achieving that in activity test class?

0

There are 0 answers