【发布时间】:2018-02-06 22:10:59
【问题描述】:
我在 Android 中有一个围绕 SharedPreferences 的实用程序包装器。我想对这个包装器进行单元测试,所以我在嘲笑我没有测试的部分:
@Before
public void setup() {
context = Mockito.mock(Context.class);
prefs = Mockito.mock(SharedPreferences.class);
editor = Mockito.mock(SharedPreferences.Editor.class);
when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(prefs);
when(prefs.edit()).thenReturn(editor);
when(editor.commit()).thenReturn(true);
}
然而,我的测试在我得到 Editor 的那一行遇到了 NPE:
SharedPreferences.Editor editor = prefs.edit();
让这个模拟工作我缺少什么?我已经看到了许多其他建议使用各种工具的 SO 答案,但如果可能的话,我强烈希望避免使用这些工具进行简单的测试。如果我确实需要使用其他工具,我应该查看什么以及该工具如何解决问题?
【问题讨论】:
-
乍一看,这看起来与我所做的相似,但你能发布 logcat 吗?
-
被测系统的构造函数是什么?
-
所以问题不在于被测对象(事实证明),而只是没有正确模拟被模拟对象上的所有方法。感谢您检查构造函数,否则这将是一个很好的起点!
标签: java android junit mockito sharedpreferences