簡體   English   中英

使用Mockito對SharedPreferences包裝器進行單元測試

[英]Unit testing a SharedPreferences wrapper with Mockito

我在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推薦使用各種工具的答案,但是如果可能的話,我強烈希望避免使用簡單的測試集。 如果確實需要使用其他工具,應該怎么看?該工具如何解決該問題?

事實證明,這個問題僅僅是缺少模擬。 我忘記分享依賴於context.getString()prefs創建行。 錯誤使我指向上面顯示的行,但事實證明上面的行具有實際的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);
}

解決方案:檢查對模擬對象使用的每個方法是否也正確模擬!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM