我是 Android 单元测试的新手,我想在现有项目中添加一些单元测试。我正在使用 MVP 设计架构。在我的演示者内部,我有一个调用PreferenceManager以获取默认值,SharedPrefences但它始终返回 null。我在 stackoverflow 上遵循了一些关于如何模拟的教程和建议PreferenceManager,SharedPreferences但我无法让它工作。这是我的演讲者课
@RunWith(MockitoJUnitRunner.class)
public class SettingsPresenterTest {
@Mock
private SettingsView mView;
@Mock
private LocalConfiguration conf;
private SettingsPresenter mPresenter;
public SettingsPresenterTest() {
super();
}
@Before
public void startUp() throws Exception {
MockitoAnnotations.initMocks(LocalConfiguration.class);
MockitoAnnotations.initMocks(PreferenceManager.class);
mPresenter = new SettingsPresenter(mView);
final SharedPreferences sharedPrefs =
Mockito.mock(SharedPreferences.class);
final Context context = Mockito.mock(Context.class);
Mockito.when(PreferenceManager.getDefaultSharedPreferences(context)).
thenReturn(sharedPrefs);
}
@Test
public void notificationsEnabledClicked() throws Exception {
boolean notifsEnabled = false;
mPresenter.notificationsEnabledClicked(notifsEnabled);
Mockito.verify(mView).setNotificationsView(notifsEnabled);
}
}
Run Code Online (Sandbox Code Playgroud)
这是SharedPreferences …