【问题标题】:Unit testing a SharedPreferences wrapper with Mockito使用 Mockito 对 SharedPreferences 包装器进行单元测试
【发布时间】: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


【解决方案1】:

问题原来只是缺少模拟。我忘了分享创建prefs 的行,它依赖于context.getString()。该错误将我指向上面显示的行,但事实证明上面的行具有实际的 NPE。 .getString() 返回测试字符串的简单模拟工作:

@Before
public void setup() {
    context = Mockito.mock(Context.class);
    prefs = Mockito.mock(SharedPreferences.class);
    editor = Mockito.mock(SharedPreferences.Editor.class);

    when(content.getString(anyInt())).thenReturn("test-string");
    when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(prefs);
    when(prefs.edit()).thenReturn(editor);
    when(editor.commit()).thenReturn(true);
}

解决方案:检查被模拟对象上使用的每个方法是否也被正确模拟了!

【讨论】:

    猜你喜欢
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2016-03-15
    相关资源
    最近更新 更多