Android:如何保存、清除然后恢复 SharedPreferences 以进行单元测试?

发布于 2024-10-08 13:43:42 字数 265 浏览 0 评论 0原文

我知道如何清除 SharedPreferences 以在定义的状态下运行我的单元测试,如下所示: PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().clear().commit()

但是,我作为我自己的应用程序的用户,我希望能够在运行单元测试后保存和恢复我喜欢的设置。

有没有一种简单的方法可以做到这一点,而无需单独手动保存和恢复每个首选项?

谢谢, 杰夫

I know how to clear SharedPreferences to run my unit tests in a defined state like this: PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().clear().commit()

However, I'd like to be able to save and restore the settings I prefer as a user of my own application after I run my unit tests.

Is there an easy way to do this without manually saving and restoring each preference item individually?

Thanks,
Jeff

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ま昔日黯然 2024-10-15 13:43:42

听起来您需要做的是提供一个 SharedPreferences 的包装器,它公开您自己的共享首选项接口。例如,

public interface PreferencesProvider {
    String getStringValue(String key);
}

无论您的测试类是什么(例如 Activity),都可以使用 PreferencesProvider 的具体实现来调用 PreferenceManager.getDefaultSharedPreferences...等。在您的测试类中,您可以替换一个假的具体实现来返回您喜欢的测试的任何内容。

这样,您的首选项提供程序就与您的应用程序类解耦,并且测试变得简单。事实上,您的测试永远不需要接触手机上存储的实际首选项。

然而,将其付诸实践需要某种依赖注入机制,例如 RoboGuice。

It sounds like what you need to do is provide a wrapper around SharedPreferences which exposes your own shared preferences interface. E.g.

public interface PreferencesProvider {
    String getStringValue(String key);
}

Whatever your class under test is (eg an Activity) can use a concrete implementation of PreferencesProvider which calls PreferenceManager.getDefaultSharedPreferences...etc. In your test class, you can substitute a fake concrete implementation to return whatever you like for your tests.

This way your preferences provider is decoupled from your application class, and testing becomes simple. In fact, your tests never need touch the actual prefs stored on your phone.

Putting this into action however requires some kind of dependency injection mechanism like RoboGuice.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文