How to safely assert that no shared preferences are present
I tried to find out how to safely assert that preferences aren't stored anywhere. It seems that haven't understood the caching mechanism yet and the docs don开发者_高级运维't clarify it. This is what I did:
File prefsFile = new File("/data/data/"+context.getPackageName() + "/shared_prefs/"
+ context.getPackageName() + "_preferences.xml");
prefsFile.delete();
assertFalse(prefsFile.exists()); // success
// This assertion could fail - why?
assertEquals(0, context.getSharedPreferences(context.getPackageName()+"_preferences",
MODE_PRIVATE).getAll().size());
Although I deleted the prefs file, it is still possible that getAll().size()
returns a non-zero value.
Could someone explain why?
I tried to find out how to safely assert that preferences aren't stored anywhere.
Why?
Could someone explain why?
Off the top of my head:
- You are not actually testing to see if the file exists before deleting it, or if the directory exists
- You are hard-coding a path that may not be correct on all devices
- You are assuming that deleting a file deletes the in-process copy of the
SharedPreferences
- You are not bothering to look at the
HashMap
returned bygetAll()
to see if your data is there, or if it is some system-supplied initial values
If you want to clear out SharedPreferences
, do not try deleting the file. Either call edit().clear().commit()
or edit().clear().apply()
on your SharedPreferences
object.
精彩评论