我正在尝试清除测试期间添加的所有 SharedPreferences。我已经阅读了一些帖子和官方文档(SharedPreferences.Editor.clear())。但是当我在运行单元测试后启动我的应用程序时,我仍然找到了测试值。
所以,在 AndroidTestCase.tearDown() ,我做这个:
public class PrivateStorageUtilsTest extends AndroidTestCase {
private static final String KEY_SP_PACKAGE = "PrivateStorageUtilsTest";
protected void setUp() throws Exception {
super.setUp();
// Clear everything in the SharedPreferences
SharedPreferences sharedPreferences = getContext()
.getSharedPreferences(KEY_SP_PACKAGE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
protected void tearDown() throws Exception {
// Clear everything in the SharedPreferences
SharedPreferences sharedPreferences = getContext().
getSharedPreferences(KEY_SP_PACKAGE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}
我在 SO 上发现的所有其他问题都是关于在 clear()
之后添加 commit()
,我已经在这里完成了。
EDIT 1添加setUp()
方法
EDIT 2提供扩展类
最佳答案
如果您使用 Espresso 中的 ActivityTestRule
,试试这个:
@Rule
public ActivityTestRule<MainActivity> activityTestRule =
new ActivityTestRule<MainActivity>(MainActivity.class) {
@Override
protected void beforeActivityLaunched() {
clearSharedPrefs(InstrumentationRegistry.getTargetContext());
super.beforeActivityLaunched();
}
};
使用 stevo.mit 的 clearSharedPrefs
的略微修改版本:
private static final String KEY_SP_PACKAGE = "PrivateStorageUtilsTest";
/**
* Clears everything in the SharedPreferences
*/
private void clearSharedPrefs(Context context) {
SharedPreferences prefs =
context.getSharedPreferences(KEY_SP_PACKAGE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.commit();
}
关于安卓单元测试: how to clear SharedPreferences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17791191/