0

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?

kostek
  • 801
  • 2
  • 15
  • 32
  • I have extensive tests [here](https://github.com/Utumno/AndroidHelpersTest/tree/master/src/gr/uoa/di/android/helpers/test). Have a look. Try with `getDefaultSharedPreferences` – Mr_and_Mrs_D Feb 13 '14 at 12:38
  • I must use my custom shared preferences, because I store there my data, and have other app components registered on their change. I could switch to use default shared preferences, but is it necessary? And testing response to changes in custom preferences is impossible? – kostek Feb 13 '14 at 13:04
  • dunno :) Try to replicate one of my tests using your prefs. I use `getContext` inside AndroidTestCase IIRC – Mr_and_Mrs_D Feb 13 '14 at 13:05

0 Answers0