如何模拟preferenceManager在Android中? [英] How to mock PreferenceManager in Android?

查看:233
本文介绍了如何模拟preferenceManager在Android中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了一个使用上下文 A类,第三方库和共享preferences preferenceManager

I've written a class that is using Context, a third party library and SharedPreferences from PreferenceManager.

这是可能的嘲笑上下文,第三方库可以使用一些模拟框架被嘲笑,但做什么用 preferenceManager

It's possible to mock Context, the third party library can be mocked using some mocking framework, but what to do with PreferenceManager?

我有两种方法:

public void saveString(ThirdPartyObject obj) {
    SharedPreferences appPreferences = 
        PreferenceManager.getDefaultSharedPreferences(mContext);
    SharedPreferences.Editor editor = appPreferences.edit();
    editor.putString(mContext.getString(
        R.string.preferences_string_name), obj.getString());
    editor.commit();
}

和相应的,即负载preferences。

and corresponding, that loads preferences.

推荐答案

它看起来并不像你真正想要 preferenceManager 的模拟实例(也就是在大多使用了 preferenceFragment preferenceActivity )。

It doesn't look like you actually want a mock instance of PreferenceManager (which is mostly used in a PreferenceFragment or PreferenceActivity).

您可能希望之一:

  1. 一个模拟共享preferences ,在这种情况下,你可以模拟上下文#getShared preferences (被称为 preferenceManager#getDefaultShared preferences 无论如何)。你可能也不得不做出一个模拟共享preferences.Editor 如果preferences被编辑,方法同上。你说你已经知道如何嘲笑的范围内,所以这应该是相当简单的。

  1. A mock SharedPreferences, in which case you can just mock Context#getSharedPreferences (which is called by PreferenceManager#getDefaultSharedPreferences anyhow). You'll probably also have to make a mock SharedPreferences.Editor if preferences are edited, as above. You say you already know how to mock the context, so this should be fairly straightforward.

要使用的实际preferences环境。这是最简单的,而不一定是一个坏主意。不要使某些它的正确清理,使您的测试不互相干扰(或根据您的测试环境,不受人工使用该应用程序的)。

To use the actual preferences in the environment. This is easiest, and not necessarily a bad idea. Do make certain it's cleaned up properly so that your tests don't interfere with each other (or, depending on your test environment, aren't affected by manual use of the app).

如果你真正的执行的需要模拟 preferenceManager 实例(如您在 $ P $得到pferenceFragment preferenceActivity ),你完全可以这样做。

If you really do want to mock PreferenceManager instance (like that you get in PreferenceFragment or PreferenceActivity), you can absolutely do so.

由于它的非最终,可以生成一个模拟 preferenceManager 共享preferences 使用的Mockito(或另一种嘲讽库),只要你有办法把它提供给你的code,无论你通常会得到一个(非测试code,这通常来自于获取preferenceManager())。

Since it's non-final, you can generate a mock PreferenceManager and SharedPreferences using Mockito (or another mocking library) as long as you have a way to provide it to your code wherever you would ordinarily get one (in non-test code, this normally comes from the getPreferenceManager()).

这篇关于如何模拟preferenceManager在Android中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆