mit*_*rop 22 android unit-testing sharedpreferences android-testing
我试图清除我测试期间添加的所有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();
}
}
Run Code Online (Sandbox Code Playgroud)
我在SO上发现的所有其他问题都是关于commit()
在clear()
我已经完成的之后添加的问题.
编辑1添加setUp()
方法
编辑2提供扩展课程
fri*_*mle 19
如果您使用的ActivityTestRule
是Espresso,请尝试以下方法:
@Rule
public ActivityTestRule<MainActivity> activityTestRule =
new ActivityTestRule<MainActivity>(MainActivity.class) {
@Override
protected void beforeActivityLaunched() {
clearSharedPrefs(InstrumentationRegistry.getTargetContext());
super.beforeActivityLaunched();
}
};
Run Code Online (Sandbox Code Playgroud)
使用稍微修改过的版本的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();
}
Run Code Online (Sandbox Code Playgroud)
Bla*_*elt 11
您应该扩展ActivityInstrumentationTestCase2
并使用getInstrumentation().getTargetContext()
以获取正在检测的目标应用程序的上下文(正在测试中)
归档时间: |
|
查看次数: |
11869 次 |
最近记录: |