我試圖使用Mockito來測試設置管理器,它通過SharedPreferences
保存數據。嘗試使用Mockito模擬SharedPreferences
由於SharedPreferences
使用Context
,我需要使用模擬類。
這是我的設置管理器類:
public class SettingsManager implements ISettingsManager {
protected SharedPreferences prefs;
public SettingsManager(SharedPreferences prefs) {
this.prefs = prefs;
}
private boolean getBooleanPreference(String key) {
return prefs.getBoolean(key, true);
}
private void setBooleanPreference(boolean enabled, String key) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(key, enabled);
editor.commit();
}
}
這是測試情況下,我寫道:
Context mContext = Mockito.mock(Context.class);
SharedPreferences mSharedPreference = Mockito.mock(SharedPreferences.class);
SharedPreferences.Editor mEditor = Mockito.mock(SharedPreferences.Editor.class, Mockito.RETURNS_DEEP_STUBS);
Mockito.when(mSharedPreference.edit()).thenReturn(mEditor);
Mockito.when(mEditor.commit()).thenReturn(true);
Mockito.when(mEditor.putBoolean(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(mEditor);
SettingsManager manager = new SettingsManager(mSharedPreference);
boolean current = manager.areNotificationsEnabled();
manager.setNotificationsEnabled(!current);
boolean newValue = manager.areNotificationsEnabled();
Assert.assertTrue(newValue != current);
問題是,當我設置setNotificationsEnabled
標誌,則newValue
保持不變的current
:SharedPreferences
不保留數據。如何在測試時將數據保存到SharedPreferences
?
我會試一試!謝謝:) –
robolectrichas非常糟糕的文檔。你可以幫我使用robolectric的任何文檔。 –