【发布时间】:2016-07-01 21:35:02
【问题描述】:
我有一个偏好实用程序类,可以在一个地方存储和检索共享偏好中的数据。
Prefutils.java:
public class PrefUtils {
private static final String PREF_ORGANIZATION = "organization";
private static SharedPreferences getPrefs(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
private static SharedPreferences.Editor getEditor(Context context) {
return getPrefs(context).edit();
}
public static void storeOrganization(@NonNull Context context,
@NonNull Organization organization) {
String json = new Gson().toJson(organization);
getEditor(context).putString(PREF_ORGANIZATION, json).apply();
}
@Nullable public static Organization getOrganization(@NonNull Context context) {
String json = getPrefs(context).getString(PREF_ORGANIZATION, null);
return new Gson().fromJson(json, Organization.class);
}
}
在 LoginActivity.java:
中显示 PrefUtils 用法的示例代码@Override public void showLoginView() {
Organization organization = PrefUtils.getOrganization(mActivity);
mOrganizationNameTextView.setText(organization.getName());
}
build.gradle 中的androidTestCompile 依赖项列表:
// Espresso UI Testing dependencies.
androidTestCompile "com.android.support.test.espresso:espresso-core:$project.ext.espressoVersion"
androidTestCompile "com.android.support.test.espresso:espresso-contrib:$project.ext.espressoVersion"
androidTestCompile "com.android.support.test.espresso:espresso-intents:$project.ext.espressoVersion"
androidTestCompile 'com.google.dexmaker:dexmaker:1.2'
androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2:'
src/androidTest/../LoginScreenTest.java
@RunWith(AndroidJUnit4.class) @LargeTest public class LoginScreenTest {
@Rule public ActivityTestRule<LoginActivity> mActivityTestRule =
new ActivityTestRule<>(LoginActivity.class);
@Before public void setUp() throws Exception {
when(PrefUtils.getOrganization(any()))
.thenReturn(HelperUtils.getFakeOrganization());
}
}
上面返回 fakeOrganization 的代码不起作用,对登录活动运行测试会导致上面 LoginActivity.java 类中定义的 mOrganizationNameTextView.setText(organization.getName()); 行中的 NullPointerException。
如何解决上述问题?
【问题讨论】:
-
我发布了一个推荐 DI 框架的答案。我仍然认为这将是一种更好的方法,但考虑到您正在为
PrefUtils使用静态单例,它不应该是必要的。你能分享你的HelperUtils吗?如果你在HelperUtils.getFakeOrganization()中设置断点,它会被命中吗? -
啊,我发现了问题,你不能单独使用 mockito 来模拟静态方法。我已经更新了我的答案,为你提供了两种可能的解决方案。
标签: android sharedpreferences mockito android-testing android-espresso